在数组索引处插入值

JavaScriptJavaScriptBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将探讨如何使用 JavaScript 在指定索引处向数组中插入值。你将学习如何使用 Array.prototype.splice() 方法,在给定索引之后插入值,且删除计数为 0。本实验将为你提供在 JavaScript 中操作数组的实践经验,并帮助你理解在插入新值时如何改变原始数组。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("JavaScript")) -.-> javascript/BasicConceptsGroup(["Basic Concepts"]) javascript(("JavaScript")) -.-> javascript/AdvancedConceptsGroup(["Advanced Concepts"]) javascript/BasicConceptsGroup -.-> javascript/variables("Variables") javascript/BasicConceptsGroup -.-> javascript/data_types("Data Types") javascript/BasicConceptsGroup -.-> javascript/arith_ops("Arithmetic Operators") javascript/BasicConceptsGroup -.-> javascript/comp_ops("Comparison Operators") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("Spread and Rest Operators") subgraph Lab Skills javascript/variables -.-> lab-28401{{"在数组索引处插入值"}} javascript/data_types -.-> lab-28401{{"在数组索引处插入值"}} javascript/arith_ops -.-> lab-28401{{"在数组索引处插入值"}} javascript/comp_ops -.-> lab-28401{{"在数组索引处插入值"}} javascript/spread_rest -.-> lab-28401{{"在数组索引处插入值"}} end

如何使用 JavaScript 在数组的特定索引处插入值

要使用 JavaScript 在数组的特定索引处插入值,请执行以下步骤:

  1. 打开终端/SSH 并输入 node 以开始练习编码。
  2. 使用 Array.prototype.splice() 方法,传入适当的索引和删除计数 0,展开要插入的给定值。
  3. insertAt 函数接受一个数组、一个索引以及一个或多个要在指定索引之后插入的值。
  4. 该函数会改变原始数组并返回修改后的数组。

以下是 insertAt 函数的实际应用示例:

const insertAt = (arr, i, ...v) => {
  arr.splice(i + 1, 0, ...v);
  return arr;
};

let myArray = [1, 2, 3, 4];
insertAt(myArray, 2, 5); // myArray = [1, 2, 3, 5, 4]

let otherArray = [2, 10];
insertAt(otherArray, 0, 4, 6, 8); // otherArray = [2, 4, 6, 8, 10]

在上述示例中,insertAt 函数用于在 myArray 数组的第二个索引之后插入值 5,并在 otherArray 数组的第一个索引之后插入值 468

总结

恭喜你!你已经完成了在数组索引处插入值的实验。你可以在 LabEx 中练习更多实验来提升你的技能。