JavaScript中splice()方法是一种常用的数组操作方法,可以用来添加、删除、替换数组的元素。它接收3个参数,第一个是开始索引,第二个是删除的元素个数,第三个是要添加的元素。
使用方法
- 删除元素:splice(startIndex, deleteCount),从startIndex开始删除deleteCount个元素,返回值是被删除的元素组成的数组。
- 添加元素:splice(startIndex, 0, addElement1, addElement2, ...),从startIndex开始添加addElement1、addElement2等元素,返回值是空数组。
- 替换元素:splice(startIndex, deleteCount, addElement1, addElement2, ...),从startIndex开始删除deleteCount个元素,并添加addElement1、addElement2等元素,返回值是被删除的元素组成的数组。
示例代码
let arr = [1, 2, 3, 4, 5, 6]; // 删除元素 let deleteArr = arr.splice(2, 3); // [3, 4, 5] console.log(deleteArr); // [3, 4, 5] console.log(arr); // [1, 2, 6] // 添加元素 arr.splice(2, 0, 3, 4, 5); console.log(arr); // [1, 2, 3, 4, 5, 6] // 替换元素 let replaceArr = arr.splice(1, 2, 'a', 'b'); // [2, 3] console.log(replaceArr); // [2, 3] console.log(arr); // [1, 'a', 'b', 4, 5, 6]