带数组参数的求和函数

时间:2018-07-29 02:01:55

标签: javascript arrays function

我正在学习javascript。我坚持进行此练习:创建一个将数组作为参数并返回数组所有元素之和的函数。 我已经编写了这段代码:

function sum(table) {
  let x = table[0];
  let y = [table.length - 1];
  let totale = 0;
  for (count = x; count <= y; count++) {
    total += x;
    x += 1;
  };
  return total;
};


console.log(sum[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

我不知道为什么未定义结果而不是55。感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

  • total不是totale
  • 函数调用需要使用括号sum([…])
  • y = table.length - 1是您想要的长度,而不是需要长度的数组
  • x = 0,您无需将其设置为数组的第一个元素
  • total += table[count];,您不需要将其设置为x或根本不需要处理x

function sum(table) {
  let x = 0;
  let y = table.length - 1;
  let total = 0;
  for (count = x; count <= y; count++) {
    total += table[count];
  };
  return total;
};


console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));

更快的解决方案

function sum(table) {
  return table.reduce((p,c)=>p+c,0);
};


console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));

答案 1 :(得分:1)

这是几件事。

您需要通过调用sum([array elements])来执行sum函数。注意()大括号 其次,count <= y将给出undefined,因为它将超过数组的长度。数组索引从0开始;

totale这里有错字。

您可以避免使用这组线

let x = table[0];
let y = [table.length - 1];

如果您只是像这样初始化循环条件语句

for (let count = 0; count < table.length; count++) 

function sum(table) {
  let x = 0
  for (let count = 0; count < table.length; count++) {
    x += table[count];
  };
  return x;
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));

另一种选择是使用reduce方法

function sum(table) {
  return table.reduce(function(acc, curr) {
    return acc += curr;
  }, 0) // 0 is the initial value
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));