Why Am I Getting This Output From This Simple Splice Command?
I have a small issue with understanding why I'm getting this output. var arr = ['a', 'b', 'c', 'd', 'e', 'f']; arr.splice(2,0,'1'); console.log(arr); var arr2 = ['a', 'b', 'c'
Solution 1:
Reading about splice method. It returns
An array containing the removed elements. If only one element is removed, an array of one element is returned.
So by doing
arr2 = arr2.splice(2,0,"2");
you overwrite initial array arr
with empty array []
returned by splice.
Solution 2:
1 - The splice method Changes the content of an array
2 - The splice method returns the element removed - ** Not original Array **
Solution 3:
So the problem is that only some methods return the original object after mutation as the return value. You can use a method decorator to keep access to the original object available even when the methods are designed differently.
constchainer = (target) =>
newProxy(target, {
get: (_, prop, receiver) =>typeof target[prop] === 'function'
? newProxy(target[prop], {
apply: (f, _, args) => {
f.apply(target, args);
return {
this: receiver,
target,
}
},
})
: target[prop],
});
const arr2 = chainer(["a", "b", "c", "d", "e", "f"])
.splice(2,0,"1").this
.splice(2,0,"2").target;
console.log(arr2);
Post a Comment for "Why Am I Getting This Output From This Simple Splice Command?"