javascript - 尝试创建一个对数字求和的 Javascript 函数

标签 javascript

我对 Javascript 非常陌生,我正在尝试编写一个对数字求和的函数。 下面的函数返回“0”而不是总和(我不知道为什么)。

function sumTo(N) {
  var total = 0
  for (var i = 0; i < N.length; i++) {
  total = total + N[i];
 }
 return total;
 };
 console.log(sumTo(1,2,3,4,5));

最佳答案

您正在尝试获取 length来自一个数字(您传递给函数的第一个数字;在您的示例中为 1 )。数字没有长度,所以你得到 undefined ,和0 < undefined为 false,因此您的循环永远不会运行。

或者:

  1. 数组传递到 sumTo

    console.log(sumTo([1, 2, 3, 4, 5]);
    // Note ----------^-------------^
    

  2. 使用 arguments自动局部变量

    for (var i = 0; i < arguments.length ++i) {
        total += arguments[i];
    }
    

  3. 使用 ES2015 的“rest”参数:

    // ES2015+ only!
    function sumTo(...values) {
       let total = 0;
       for (let i = 0; i < values.length; ++i) {
           total += values[i];
       }
       return total;
    }
    

    由于此时您处于 ES2015,因此您可以使用 reduce使用箭头函数(总和是 reduce 的完美用例):

    // ES2015+ only!
    function sumTo(...values) {
       let total = values.reduce((a, b) => a + b);
       return total;
    }
    

    或者for-of ,另一个 ES2015 的事情:

    // ES2015+ only!
    function sumTo(...values) {
       let total = 0;
       for (let value of total) {
           total += value;
       }
       return total;
    }
    

关于javascript - 尝试创建一个对数字求和的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40044995/

相关文章:

javascript - 一旦用户开始在文本字段中输入,您如何检查复选框?如果 javascript/html 中的文本字段为空,也取消选中复选框

javascript - foreach 在 laravel 中使用 javascript 循环

javascript - 如何使用 asp.net 禁用 Internet explorer 中的退格键

javascript - 在 HTML 中添加数值

javascript - 重新启用点击事件

javascript - Facebook XFBML登录后,通过JavaScript获取用户信息

javascript - 带有选择框的 JQuery

javascript - 我想用 Jquery AciTree 迭代选中的复选框

javascript - 如何将值从 Javascript 传递给 td?

javascript - 如何创建具有最大元素的唯一键数组?