JavaScript Array forEach 函数不起作用?

问题描述 投票:0回答:3

我尝试对W33学校的javascript代码进行一些更改以了解差异 在 forEach 和 map 之间,有谁可以告诉我为什么这段代码的输出仍然是:

45,4,9,16,25

而不是

90,8,18,32,50

forEach 不是意味着对这个数组中的每个元素调用一个函数吗?我知道我不应该使用 return,因为 forEach 不会返回有效结果。

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>

javascript
3个回答
3
投票

value * 2
执行计算,但它不对计算结果执行任何操作。您可以将该行更改为
value = value * 2
,这会将计算结果分配给
value
变量。但是,这仍然不会改变数组中的值,因为
value
变量仅限于函数的范围。

这是因为当您将数字传输到另一个变量时,您只是传输,而不是引用。即

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

这与数组和对象不同,其中引用被传递:

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

因此,修复代码的一种方法可能是操作数组,即

const numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);

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

// numbers is [90,8,18,32,50]

这有效。不过,我会推荐简单的

map
而不是
forEach
Array#map
使用每个函数调用的返回值来替换数组中的每一项。

const numbers = [45, 4, 9, 16, 25];
const doubles = numbers.map(myFunction);

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

// numbers is [45,4,9,16,25]
// doubles is [90,8,18,32,50]

0
投票

这是因为您没有用相乘的值重新设置数字的值。

需要根据地图功能里面的

numbers[index]
来设置。

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

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

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

0
投票

函数

myFunction
基本上什么都不做,它将当前值加倍,并且不做任何事情。在你的情况下,你需要改变数组。但改变你正在遍历的数组并不是一个好主意。

为了实现您的目标,我建议使用

map
函数创建一个新数组。

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

const doubledNumbers = numbers.map(val => val * 2); // [90, 8, 18, 32, 50]
document.getElementById("demo").innerHTML = doubledNumbers;
© www.soinside.com 2019 - 2024. All rights reserved.