迹忆客 专注技术分享

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

JavaScript 中替换数组的第一个元素

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

要替换数组的第一个元素,请使用括号表示法 [] 访问索引 0 处的数组元素并使用替换项更改其值,例如 arr[0] = 'replacement'

// 👇️ with Mutation
const arr1 = ['Alice', 'Jiyik', 'Charlie'];

arr1[0] = 'John';
console.log(arr1); // 👉️ ['John', 'Jiyik', 'Charlie']

// 👇️ without Mutation ------
const arr2 = ['Alice', 'Jiyik', 'Charlie'];

const newArr = ['Replacement Here', ...arr2.slice(1)];
console.log(newArr); // 👉️ ['Replacement Here', 'Jiyik', 'Charlie']

console.log(arr2); // 👉️ ['Alice', 'Jiyik', 'Charlie']

JavaScript 中替换数组的第一个元素

我们的第一个示例展示了如何通过使用方括号 [] 直接访问索引 0 处的数组元素并更改其值来替换数组中的第一个元素。

索引在 JavaScript 中是从零开始的,这意味着第一个数组元素的索引为 0,最后一个元素的索引为 array.length - 1

为索引 0 处的数组元素分配新值会更改原始数组的内容。 如果您不想更改数组,请改用第二种方法。

第二个示例使用展开运算符 ...Array.slice 方法来获取包含替换项的新数组,而不更改原始数组。

我们传递给 slice 方法的参数是起始索引——要包含在新数组中的第一个元素的索引。

slice 方法返回一个新数组,而不改变原始数组。

考虑展开运算符 (...) 的一种简单方法是,我们从数组中取出元素并将它们解包到新数组中。

确保在调用 slice 方法之前包含替换元素,因为顺序会保留在新数组中。

这是替换数组第一个元素的更间接的方法,但它不会更改原始数组的内容,而这正是我们大多数时候想要的。

在代码库中很难跟踪和推断突变,尤其是当同一个数组或对象在不同位置发生多次突变时。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便