使用 JavaScript 更新数组中的所有元素
要更新数组的所有元素,请调用数组的 forEach()
方法,并向其传递一个函数。 为数组中的每个元素调用该函数,并允许我们更新数组的值。
const arr = ['zero', 'one', 'two'];
arr.forEach((element, index) => {
arr[index] = element + index;
});
// 👇️ ['zero0', 'one1', 'two2']
console.log(arr);
如果我们不想更改原始数组,请向下滑动到下一个副标题。
我们传递给 Array.forEach
方法的函数会为数组中的每个元素调用。
每次,它都会传递以下 3 个参数:
- 元素
- 指数
- 阵列
在每次迭代中,我们使用索引来更新当前数组元素的值。
请注意
,这会原地更改原始数组。
不改变原始数组的替代解决方案是使用 Array.map 方法。
使用 map() 更新数组中的所有元素
更新数组中的所有元素:
-
调用
map()
方法迭代数组。 - 在每次迭代中,返回更新后的值。
-
map()
方法将返回一个包含更新值的新数组。
const arr = ['zero', 'one', 'two'];
const newArr = arr.map((element, index) => {
return element + index;
});
// 👇️ ['zero0', 'one1', 'two2']
console.log(newArr);
// 👇️ ['zero', 'one', 'two']
console.log(arr);
我们传递给 map() 方法的函数会为数组中的每个元素调用。
它传递了以下 3 个参数:
- 元素
- 指数
- 数组
我们从回调函数返回的任何内容都会添加到 map() 方法返回的新数组中。
map
方法不会改变原始数组,它会返回一个新数组。
我们选择哪种方法是个人喜好的问题。 我会使用 map()
方法,因为我发现很难在整个代码库中推理和跟踪执行的堆栈。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。