Skip to content

给数组最后一位添加元素

js
let arr = [1, 2, 3];
let longth = arr.push(4); // 返回数组长度
console.log(longth);
let arr = [1, 2, 3];
let longth = arr.push(4); // 返回数组长度
console.log(longth);

给数组第一位添加元素

unshift(value);在数组的头部添加一个或多个元素,并返回数组的新长度

js
let arr = [1, 2, 3, 4, 5];
var length = unshift(0);
console.log(arr, length); //arr的值为[0,1,2,3,4,5];length的值为更改后数组的长度6;
let arr = [1, 2, 3, 4, 5];
var length = unshift(0);
console.log(arr, length); //arr的值为[0,1,2,3,4,5];length的值为更改后数组的长度6;

根据下标在数组指定位置插入元素

使用 splice 插入、删除或替换数组的元素

js
/* 使用splice()方法会影响原数组 */
let word_arr = ["depress", "destination", "motion", "rise", "rouse"];
console.log(word_arr);
console.log(word_arr.splice(1, 0, "up", "pitch", "up"));
console.log(word_arr);
/* 使用splice()方法会影响原数组 */
let word_arr = ["depress", "destination", "motion", "rise", "rouse"];
console.log(word_arr);
console.log(word_arr.splice(1, 0, "up", "pitch", "up"));
console.log(word_arr);

根据提供的元素在指定位置增加元素

for...of 遍历中增加元素:

js
let list = ["a", "b", "c", "d"];
for (let item of list) {
  if (item === "a") {
    list.splice(1, 0, "e");
  }
  console.log(item);
}
let list = ["a", "b", "c", "d"];
for (let item of list) {
  if (item === "a") {
    list.splice(1, 0, "e");
  }
  console.log(item);
}

输出:

a e b c d

forEach 遍历中增加元素:

js
let list = ["a", "b", "c", "d"];

list.forEach((item, idx) => {
  if (item === "a") {
    list.splice(1, 0, "e");
  }
  console.log(item);
});
let list = ["a", "b", "c", "d"];

list.forEach((item, idx) => {
  if (item === "a") {
    list.splice(1, 0, "e");
  }
  console.log(item);
});

输出:

a e b c

咦,少了个'd'! 可以看到,其实 forEach 遍历次数在一开始就已确定,所以最后的'd'没有输出出来,这是 forEach 和 for 遍历数组的一个区别,另一个重要区别是 forEach 不可用 break, continue, return 等中断循环,而 for 则可以。

总之,在遍历数组过程中,对数组的操作要非常小心,这一点 python、js 很相似,因为两门语言中,对象/字典和数组都是引用,都为可变对象。