使用 slice()
方法
slice()方法返回一个新的数组对象,原始数组不会被改变,slice()方法不仅仅作用于数组,也能作用于字符串。slice()方法有两个参数,第一个参数是提取起始处(start),第二个参数是提取终止处(end)。
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]
注意:第一个参数索引是包含该数据,第二个参数索引不包含该数据
使用 splice()
方法
splice()方法能替换和移除已存在的元素和添加新的元素。同时,splice()方法是会直接修改原数组。
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]
splice()方法有三个参数:
第一个参数表示要开始改变数组的位置。
第二个参数一个整数,表示数组中要从开始删除的元素数量。
第三个参数从 开始要加入到数组中的元素,如果不指定任何元素,splice()
将只从数组中删除元素。
删除情况:当没有第三个参数时,数组为删除元素。
const myFish = ["angel", "clown", "drum", "mandarin", "sturgeon"];
const removed = myFish.splice(3, 1);
// myFish 是 ["angel", "clown", "drum", "sturgeon"]
// removed 是 ["mandarin"]
替换情况:当三个参数都存在并且第二个参数为正整数时,数组为替换元素。
const myFish = ["angel", "clown", "drum", "sturgeon"];
const removed = myFish.splice(2, 1, "trumpet");
// myFish 是 ["angel", "clown", "trumpet", "sturgeon"]
// removed 是 ["drum"]
新增情况:当三个参数都存在而第二个参数为0时,数组为新增元素。
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2, 0, "drum", "guitar");
// myFish 是 ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
// removed 是 [],没有移除的元素
使用扩展运算符
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [...arr1, 6, 7];