JavaScript 在数组中插入元素程序

要理解此示例,您应了解以下 JavaScript 编程 主题


示例 1:使用 splice() 向数组添加元素

// program to insert an item at a specific index into an array

function insertElement() {
    let array = [1, 2, 3, 4, 5];

    // index to add to
    let index = 3;

    // element that you want to add
    let element = 8;
  
    array.splice(index, 0, element);
    console.log(array);
}

insertElement();

输出

[1, 2, 3, 8, 4, 5]

在上面的程序中,使用 splice() 方法将元素插入数组的特定索引。

splice() 方法添加和/或删除元素。

splice() 方法中,

  • 第一个参数指定要插入元素的索引。
  • 第二个参数(此处为0)指定要删除的元素数量。
  • 第三个参数指定要添加到数组中的元素。

示例 2:使用 for 循环向数组添加元素

// program to insert an item at a specific index into an array

function insertElement() {
    let array = [1, 2, 3, 4];

    // index to add to
    let index = 3;

    // element that you want to add
    let element = 8;
  
    for (let i = array.length; i > index; i--) {

        //shift the elements that are greater than index
        array[i] = array[i-1];
    }

    // insert element at given index
    array[index] = element;

    console.log(array);
}

insertElement();

输出

[1, 2, 3, 8, 4]

在上面的程序中,

  • for 循环用于遍历数组元素。
  • 元素被添加到给定索引。
  • 所有索引大于给定索引的元素都向右移动一个位置。

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战