Reputation: 13
Apologies if this has been asked in other ways but my google-fu is lacking today. I just started learning Javascript today and I'm having an issue passing arrays into functions. I am trying to add the values of two arrays at each index, but sololearn's code playground is giving me an error when it tries to read the length of arr1 in the second function: "Uncaught TypeError: Cannot read property 'length' of undefined".
I have tried changing the iterator to "i <=6", but then it tells me it cannot read the property at index 0 of undefined at the "sum[i]..." line. I've also tried declaring the arrays with var instead of let.
Can anyone offer me insight as to why the array isn't passing into the function properly?
function generateStats(){
let race = "halfOrc";
const halfOrc = [2,1,0,0,0,0];
let stats = [0,0,0,0,0,0];
switch(race){
case "halfOrc":
stats = sumArray(stats,halfOrc);
break;
//more code
}
function sumArray(arr1,arr2){
var sum = [];
for (let i = 0; i <= arr1.length;) {
sum[i] = arr1[i] + arr2[i];
i++;
return sum
}
}
Upvotes: 1
Views: 1915
Reputation: 1
array of length 2 for example has valid indices of 0 and 1 so, never use <= when comparing to array.length -
you're also returning in the for loop so only the first iteration will run –
quick fix ... change i <=
to i <
and move return sum
after }
and move i++
to the for loop line .
Here's your code - it works now
function generateStats() {
let race = "halfOrc";
const halfOrc = [2, 1, 0, 0, 0, 0];
let stats = [0, 0, 0, 0, 0, 0];
switch (race) {
case "halfOrc":
stats = sumArray(stats, halfOrc);
break;
//more code
}
console.log(stats);
}
function sumArray(arr1, arr2) {
var sum = [];
for (let i = 0; i < arr1.length; ++i) {
sum[i] = arr1[i] + arr2[i];
}
return sum
}
generateStats();
Upvotes: 2