I want to add 2 numbers at the beginning of array using splice method . can some one explain why the 2nd method gives me an empty array as output?.
const arrayold = [5, 6, 7, 8];
arrayold.splice(0, 0, 1, 2);
const arrayNew = arrayold;
console.log(arrayNew);
const arrayold = [5, 6, 7, 8];
const arrayNew = arrayold.splice(0, 0, 1, 2);
console.log(arrayNew);
CodePudding user response:
Because it returns a list of deleted objects!
The actual modified thing is in the variable/s
Like it is in the first case, you decided not to do var o1=o2.splice( /*arguments*/ )
; but var _new=_old
instead.
You can read more at mdn about what splice modifies and what it returns! So it is possible when you have inner Peace, amen
CodePudding user response:
splice() modifies the source array and returns an array of the removed items. Since you didn't ask to remove any items, you get an empty array back. It modifies the original array to insert your new items
CodePudding user response:
const arrayold = [5, 6, 7, 8];
const arrayNew= arrayold.splice(0, 0, 1, 2);
console.log(arrayNew);
The splice method generally return the removed item from an array. So In your second sceanrio arrayold.splice(0,0,1,2) you are not removing any element as you have mentioned 0 that's why it is giving you empty array