简体   繁体   中英

JavaScript Array forEach function not working?

I tried to do some changes in the W33 school's javascript code to learn about the difference between forEach and map, is there anyone can please tell me why the output of this code is still:

45,4,9,16,25

instead of

90,8,18,32,50

Isn't it forEach means call a function to every element in this array? I know I should not use return because the forEach does not return valid result.

 const numbers = [45, 4, 9, 16, 25]; numbers.forEach(myFunction); document.getElementById("demo").innerHTML = numbers; function myFunction(value, index, array) { value * 2; }
 <.DOCTYPE html> <html> <body> <h2>JavaScript Array.forEach()</h2> <p>Calls a function once for each array element.</p> <p id="demo"></p> </body> </html>

The line value * 2 performs a calculation, but it doesn't do anything with the result of that calculation. You could change the line to value = value * 2 and that would assign the result of the calculation to the value variable. However, that still wouldn't change the values in the array, because the value variable is restricted to the scope of the function.

This is because when you transfer a number to another variable, you are only transferring the value , not the reference. ie

let a = 1;
let b = a;
a = 2; // a is 2, b is 1

This is different to arrays and objects, where the reference is transferred:

let a = [1];
let b = a;
a[0] = 2; // a[0] is 2, b[0] is 2

So a way to fix your code might be to manipulate the array instead, ie

numbers.forEach(myFunction);

function myFunction(value, index, array) {
  array[index] = value * 2;
}

This works. However, I would recommend the simplicity of map instead of forEach . Array#map uses the return value of each function call to replace each item in the array.

numbers.map(myFunction);

function myFunction(value, index, array) {
  return value * 2;
}

The function myFunction basically does nothing, it doubles the current value and does nothing with it. In your case, you need to mutate the array. But it's not a good idea to mutate the array which you're traversing.

To achieve your goal, I recommend creating a new array using the map function.

const numbers = [45, 4, 9, 16, 25];

const doubledNumbers = numbers.map((value) => val * 2); // [90, 8, 18, 32, 50]
document.getElementById("demo").innerHTML = doubledNumbers;

This is because you are not re-setting the value of numbers with the multiplied value.

You need to set it according to numbers[index] inside the map function.

const numbers = [45, 4, 9, 16, 25];

numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = numbers;

function myFunction(value, index, array) {
  numbers[index] = value * 2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM