javascript - 谁能解释为什么第一个例子的返回值是 NaN ?第二个例子很好

标签 javascript

谁能解释一下为什么第一个例子的返回值是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/

相关文章:

javascript - 尝试将变量放入 Jquery 的选择器中

javascript - 过滤器不能以 Angular 工作?

javascript - 如何将 ffmpeg 与 Nuxt 一起使用?

javascript - Firebase onDisconnect 如何触发其他功能

javascript - VueJs : How to pass a 'computed function' value from child component to the parent component using $emit(optionalPayload) and $on?

javascript - 我可以让输入元素填充表格列的宽度吗?

javascript - 将值从组合框发送到文本区域

javascript - 克隆数据数组模板时累积的类

javascript - Pusher - 私有(private) channel 订阅

javascript - 需要一键调用 4 个函数,忽略参数