Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Khác biệt 저 cấp Slice và Splice trong JavaScript

Khác biệt cơ bản:

  • splice(): Thay đổi original array, trả về mảng các item bị xóa.
  • slice(): Không thay đổi original, trả về mảng slice (shallow copy).

Ví dụ

// splice mutates array
let arr = [1, 2, 3, 4, 5];
console.log(arr.splice(2)); // [3, 4, 5] - xóa từ index 2 đến cuối

// slice doesn't mutate
let arr2 = [1, 2, 3, 4, 5];
console.log(arr2.slice(2)); // [3, 4, 5] - copy từ index 2

console.log("\nAfter operations:");
console.log(arr);   // [1, 2]
console.log(arr2);  // [1, 2, 3, 4, 5]

Kết quả

[ 3, 4, 5 ] [ 3, 4, 5 ]
After Changing the arrays
[ 1, 2 ] [ 1, 2, 3, 4, 5 ]

Chi tiết:

slice(start, end)splice(start, deleteCount, ...items)
MutateKhôngCó
Trả vềMảng mới (copy)Mảng item bị xóa
Tham sốstart, end (exclusive)start, deleteCount, itemsToInsert
Dùng choLấy subarray, cloneXóa, chèn, thay thế element

slice(-2) lấy 2 phần tử cuối. splice(1, 0, 'a', 'b') chèn 'a','b' tại index 1 không xóa.