示例 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
循环用于遍历数组元素。- 元素被添加到给定索引。
- 所有索引大于给定索引的元素都向右移动一个位置。
另请阅读