迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

使用 JavaScript 更新数组中的所有元素

作者:迹忆客 最近更新:2022/11/28 浏览次数:

要更新数组的所有元素,请调用数组的 forEach() 方法,并向其传递一个函数。 为数组中的每个元素调用该函数,并允许我们更新数组的值。

const arr = ['zero', 'one', 'two'];

arr.forEach((element, index) => {
  arr[index] = element + index;
});

// 👇️ ['zero0', 'one1', 'two2']
console.log(arr);

如果我们不想更改原始数组,请向下滑动到下一个副标题。

我们传递给 Array.forEach 方法的函数会为数组中的每个元素调用。

每次,它都会传递以下 3 个参数:

  1. 元素
  2. 指数
  3. 阵列

在每次迭代中,我们使用索引来更新当前数组元素的值。

请注意 ,这会原地更改原始数组。

不改变原始数组的替代解决方案是使用 Array.map 方法。


使用 map() 更新数组中的所有元素

更新数组中的所有元素:

  1. 调用 map() 方法迭代数组。
  2. 在每次迭代中,返回更新后的值。
  3. 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 个参数:

  1. 元素
  2. 指数
  3. 数组

我们从回调函数返回的任何内容都会添加到 map() 方法返回的新数组中。

map 方法不会改变原始数组,它会返回一个新数组。

我们选择哪种方法是个人喜好的问题。 我会使用 map() 方法,因为我发现很难在整个代码库中推理和跟踪执行的堆栈。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便