ECMAScript proposal "Change Array by copy" by Robin Ricard and Ashley Claymore has been merge into ECMAScript standard. This proposal brings a lot of new toys, one of which is new array method: toSpliced()
.
The toSpliced()
method is similar to splice
array.toSpliced(start, deleteCount, item1, item2, ...)
The only difference is that it does not change the original array, calling this method returns a changed copy of the original array instead of the deleted array.
// splice()
const originalArr = [1,2,3];
const targetArr = originalArr.slice(1, 1, 5);
console.log(targetArr) // [2]
// The original array is mutated
console.log(originalArr) // [1,5,3]
// toSplice()
const originalArr = [1,2,3];
const targetArr = originalArr.toSplice(1, 1, 5);
console.log(targetArr) // [1,5,3];
// The original array is not affected
console.log(originalArr) // [1,2,3]
For more information, check out the following resources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSpliced
Top comments (0)