js 数组splice/slice方法区别

137 阅读1分钟

slice()

slice()  方法返回一个新的数组对象,

  • 这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括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"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

从倒数第n个开始取

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

取正数第2个 到 倒数第1个

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

浅拷贝

console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

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"]