我正在学习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。感谢您的帮助。
答案 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]));