admin管理员组文章数量:1418627
Can someone please explain to me what I am doing wrong here... This code is from eloquent javascript and it works fine
function sum(array) {
let total = 0;
for (let value of array) {
total += value;
}
return total;
}
Can someone please explain to me what I am doing wrong here... This code is from eloquent javascript and it works fine
function sum(array) {
let total = 0;
for (let value of array) {
total += value;
}
return total;
}
And this is what I wrote for the exercise but returns NaN..
function sum(numArray) {
let add = 0;
for (let a = 0; a <= numArray.length; a++) {
let addIndex = numArray[a];
add += addIndex;
}
return add;
}
Share
Improve this question
edited Sep 19, 2018 at 15:53
OJay
asked Sep 19, 2018 at 15:49
OJayOJay
631 silver badge6 bronze badges
1
- What values are actually in that array? I suspect that not everything in there is a 'number'. – ouflak Commented Sep 19, 2018 at 16:27
5 Answers
Reset to default 4Your for
loop goes out of array indexes. You have to use:
a < numArray.length
Instead of:
a <= numArray.length
You simply add undefined
to add
, because you run the index count to long.
for (let a = 0; a <= numArray.length; a++) {
// ^ wrong, takes last index + 1
function sum(numArray) {
let add = 0;
for (let a = 0; a < numArray.length; a++) {
let Addindex = numArray[a];
add += Addindex;
}
return add;
}
console.log(sum([1, 2, 3, 4]));
The issue is because of this a <= numArray.length
. Change it to a < numArray.length
. This case a[5] that is the 6th element or the element at 5th index is undefined as the array starts from 0 index. So it will add an undefined
with previously added number and hence it will be NaN
function sum(numArray) {
let add = 0;
for (let a = 0; a < numArray.length; a++) {
let Addindex = numArray[a];
add += Addindex;
}
return add;
}
console.log(sum([1, 2, 3, 4, 5]))
You're getting an out-of-bounds error. In your for
loop, you can change it to:
for (let a = 0; a < numArray.length; a++) {
OR
for (let a = 0; a <= numArray.length - 1; a++) {
The latter works too, but is harder to read.
You can also write a function that has two parameters, an array and a callback function that adds the values of the array like
function forEach(array, arrayAdder){
for (var i = 0; i < array.length; i ++)
arrayAdder(array[i]) ;
}
We can now initialize both the array and the sum like
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], sum = 0;
After that we pass it into the function like this
forEach(array, function(number){
sum += number ;
});
Then print the answer
console.log(sum);
本文标签: javascriptWrite a sum() function that takes an array of numbersStack Overflow
版权声明:本文标题:javascript - Write a sum() function that takes an array of numbers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745295940a2652077.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论