Code 1:
let targetArr = ["hello", "world", "my", "name"];
let errnewArr = Array.from(targetArr).splice(2, 1);
console.log("errnewArr array : "+errnewArr.length);
Code 2:
targetArr = ["hello", "world", "my", "name"];
let newArr = Array.from(targetArr);
newArr.splice(2, 1);
console.log("new array : "+newArr.length);
As you can see the code are similar logic, just the splice method is place after the Array.from
or in a newArr
, but the result is very different, the errnewArr
got the length: 1, but the new array
got the length: 3.
Why the result is look like that?
3
Answers
splice return the deleted elements and change the array in place
The difference in the results between the two code snippets is due to the way the
splice()
method works and how it affects the original array and the newly created array.In Code 1, the
Array.from(targetArr)
creates a new array using the elements fromtargetArr
, and then thesplice(2, 1)
method is called on that new array. Thesplice()
method modifies the array in place by removing one element at index 2. Thesplice()
method returns an array containing the removed elements, soerrnewArr
ends up being an array with the removed element "my".Therefore, the length of
errnewArr
is 1.In Code 2,
Array.from(targetArr)
also creates a new array with the elements fromtargetArr
, but this time, thesplice(2, 1)
method is called on thenewArr
array itself. Thesplice()
method modifies the array in place, just like before, but sincenewArr
is a separate array fromtargetArr
, the modification doesn’t affect the originaltargetArr
array. The element "my" is removed fromnewArr
, and the resulting array has a length of 3.To summarize, the difference in the results is because in Code 1, the
splice()
method is called on the new array created byArray.from()
, while in Code 2, thesplice()
method is called on a separate array (newArr
) created byArray.from()
.One is the target and the other is the return