谁能解释一下为什么第一个例子的返回值是NaN?第二个例子很好。
例如:1
function mul(a,...b){
for (var i=0; i<b.length; i++);
return b[i] *= a;
}
例如:2
function mul(a,...b){
for (var i=0; i<b.length; i++)
b[i] *= a;
return b;
}
console.log(mul(2,1,1,1));
最佳答案
因为在第一个示例中,b[i]
是未定义
。
假设您正在循环长度为 3 的数组。在循环中,索引 i
涵盖:0, 1, 2
但是,在最后一次循环迭代之后,i
再次递增,现在为 3
。当您尝试访问 b[3]
时,如果 b
的长度为 3,则它是未定义的。在数学运算中使用 undefined 会产生 NaN
。
for (var i=0;i<b.length;i++); // i loops from 0 to the length of the array
return b[i]*=a; // i is now outside the bounds of the array
关于javascript - 谁能解释为什么第一个例子的返回值是 NaN ?第二个例子很好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42287083/