splice与slice的区别
- splice用于在数组某个位置添加或删除元素
<script>
// 注:splice方法会改变原来的数组,用于在数组的某个位置添加或删除元素
let color = ["Red", "Green", "Blue", "Yellow"];
console.log(color); //["Red", "Green", "Blue", "Yellow"]
let arr1 = color.splice(2, 0, "Pink"); //2表示从下标2开始(包含下标2),不删除元素,并在该位置添加"Pink"
console.log(color); //["Red", "Green", "Pink", "Blue", "Yellow"]
console.log(arr1); //arr1为删除的元素组成的数组,[]
let fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits); //["Banana", "Orange", "Apple", "Mango"]
let arr2 = fruits.splice(2, 1, "Peach"); //2表示从下标为2开始(包含下标2),删除1个元素,替换为"Peach"
console.log(fruits); //["Banana", "Orange", "Peach", "Mango"]
console.log(arr2); //["Apple"]
</script>
- slice用于截取数组中若干个连续的元素
<script>
// 注:slice方法并不会改变原来的变量,用于截取数组中若干个下标连续的元素
let color = ["Red", "Green", "Blue", "Yellow"];
console.log(color); //["Red", "Green", "Blue", "Yellow"]
let newColor = color.slice(2, 3); //从下标2开始截取(包括下标2),到下标3(不包括下标3)
console.log(newColor); //["Blue"]
</script>