[英]Why Javascript console.log result is NaN when I tried Repeat a string a specified times
function repeatS(srr, num) {
if (num <= 0) {
return "";
}
var result = "";
for (var i = 0; i < num; i++) {
result = +srr;
}
return result;
}
console.log(repeatS("ahfidhfd", 3));
strong text 强文本
Here is my question, the result is Nan, anyone knows what might be the problem here... 这是我的问题,结果是南,任何人都知道这可能是问题所在...
result = +srr;
应该
result += srr;
You use an unary plus +
for converting a string to a number, but you need to assign the value to the left hand variable. 您可以使用一个一元加
+
一个字符串转换为一个数字,但你需要赋值给左边的变量。
function repeatS(srr, num) { if (num <= 0) { return ""; } var result = ""; for (var i = 0; i < num; i++) { result += srr; } return result; } console.log(repeatS("ahfidhfd", 3));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.