1

I just started learning arrays in school today and I am trying to add 5 to all of my values in my array. In the console log all of the values are being added with 5 but then when it come to printing the values outside the loop in the console log it prints the original values from the array. Here is the link so you can see my code. If you press the view code button it should let you play with my code. https://studio.code.org/projects/applab/SouZg_T_mKFUkTRlRPZHaaBXOO71-CGyy7dW6nF57qU

var myArray = [];
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));

console.log("Before: " + myArray);

var myNewArray = (myArray[i]);


for (var i = 0; i < myArray.length; i++) {
  //var myNewArray = myArray;

  myNewArray = (myArray[i]+5);
  //console.log(myArray[i]+5);
  console.log(myNewArray);

  //console.log("After: " + myArray);
}


console.log("After: " + myNewArray);
catpat4
  • 19
  • 1
  • 6

1 Answers1

1

Reassign the new value to that array and then after reassigning all, loop through it again, printing each one. Or you can just print the entire array

for (var i = 0; i < myArray.length; i++) {
  myArray[i] = myArray[i] + 5; //i am reassigning the new value here
}

//console.log(myArray); //printing the entire array here

for(var i = 0; i < myArray.length; i++){
  console.log("After: " + myArray[i]);
}
Abana Clara
  • 4,602
  • 3
  • 18
  • 31