function NumberAddition(str) {
var nstr = str.match(/[0-9]+/g);
var total = 0;
if (nstr !== null)
for (var i = 0; i < nstr.length; i++) {
total += nstr[i]*1;
}
// code goes here
return total;
}
我正在查看coderbyte.com中的答案,这是其中之一。我的问题是关于total += nstr[i]*1
部分。如果我删除*1
,则答案会连接到“2344”。但答案应该是23 + 4 + 4 = 31。为什么是这样?无法理解涉及号码添加的功能
太棒了!谢谢你的协助。 – Connor 2014-09-01 22:54:31
@ Connor注意到“转换”为数字只是为了评估表达式,'nstr [i]'仍然是一个字符串。 – RobG 2014-09-01 23:07:53