Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 在数组中插入项目的程序

用于在数组中插入项目的 JavaScript 程序

在本例中,您将学习编写一个 JavaScript 程序,该程序将在特定索引处插入一个项目到数组中。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 数组 splice() JavaScript for 循环 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 循环用于遍历数组元素。 元素被添加到给定的索引中。 索引大于给定索引的所有元素都向右移动一步。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4