0

I'm a beginner of JavaScript.I learn the course on Udacity. And there is a simple question about Array practice but I can't figure out why. I will be very appreciate if anyone can answer me,thanks!

practice:

  • Programming Quiz: Another Type of Loop (6-8)

  • QUIZ REQUIREMENTS

  • Use the existing test variable and write a forEach loop

  • that adds 100 to each number that is divisible by 3.

  • Things to note:

    • Inside the loop, you must use an if statement to verify code is divisible by 3
    • Inside the loop, you can update an element ONLY by using the arrayName[index]
    • Outside the loop, you can use console.log to verify the test variable */

    var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4, 19, 300, 3775, 299, 36, 209, 148, 169, 299, 6, 109, 20, 58, 139, 59, 3, 1, 139 ];

Answer:

test.forEach(function (value,index,array){
    if (value % 3 ===0){
    array[index] +=100;
}
    return value;
});
console.log(test);   

My problem is why can't I use value +=100:

test.forEach(function (value,index,array){
    if (value % 3 ===0){
    value +=100;
}
return value;
});

what's the difference?

Thanks!!!!!!!!1

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • `value` is a variable and changing it doesn't change the array. `array[index]` is changing the array. It's also part of the instructions: "*Inside the loop, you can update an element ONLY by using the arrayName[index]*" – VLAZ Mar 15 '22 at 10:38
  • When using for each the fist arg that is passiing in the function is the current value of the array in the place of th loop the secound is the index of the value and last is the array. when you are adding to the value is doesnt have reffence the element in the array so you need to change that array itself and not thar value passing in the fuction – ShobiDobi Mar 15 '22 at 10:41

0 Answers0