Slice 和 Splice 方法在 Javascript 中的底層差異
slice 和 splice 之間最基礎的區別是 −
splice() 更改其呼叫的原陣列,然後將移除的項作為新陣列物件返回到陣列中。
slice() 不會更改原陣列,並且也會返回已切片的陣列。
示例
// splice changes the array let arr = [1, 2, 3, 4, 5]; console.log(array.splice(2)); //slice doesn't change original one let arr2 = [1, 2, 3, 4, 5]; console.log(array2.slice(2)); console.log("
After Changing the arrays"); console.log(array); console.log(array2);
輸出
[ 3, 4, 5 ] [ 3, 4, 5 ]
更改陣列後
[[ 1, 2 ] [ 1, 2, 3, 4, 5 ]
廣告