简体   繁体   English

为什么当我尝试重复指定次数的字符串时Javascript console.log结果为NaN

[英]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.

相关问题 Javascript 为什么 console.log(typeof &quot;Not a Number&quot; - &quot;Number&quot;) 打印 &#39;NaN&#39;? - Javascript why console.log(typeof "Not a Number" - "Number") prints 'NaN'? 当console.log()时获得NaN - Getting NaN when console.log() 如何在javascript代码中获取console.log的结果字符串? - How to get result string of console.log in javascript code? Javascript:如何将console.log结果返回为字符串形式? - Javascript: How can I return console.log result into string form? 当我在浏览器中输入 console.log 时,为什么谷歌浏览器没有显示结果? - When I typed console.log to my browser, why does Google Chrome not showing me the result? 在 javascript 中,为什么在我 console.log 时显示,但在我返回时不显示 - In javascript, why is this showing when I console.log but not when I return 为什么不Console.log结果? - Why Wont It Console.log The Result? Javascript:为什么在console.log中调用变量时将“()”放在变量之后? - Javascript: Why do I put “()” after a variable when calling it in console.log? 为什么即使我成功循环 100 次并打印 console.log,我也无法在 javascript 控制台中看到 100 次输出? - Why i am not able to see output for 100 times in the javascript console even if i am successfully looping through 100 times and printing console.log? 当我使用 console.log 矩阵时,为什么会有这三个 [0][0][0][0][0][0] ? - why is there three of these [0][0][0][0][0][0] when i console.log matrix?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM