示例 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()
方法添加和/或删除项目。
在
第一个参数指定要插入项目的索引。
第二个参数(此处为 0)指定要删除的项目数。
第三个参数指定要添加到数组中的元素。
splice()
方法中,
示例 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
循环用于遍历数组元素。
元素被添加到给定的索引中。
索引大于给定索引的所有元素都向右移动一步。