skip to Main Content

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


  1. splice return the deleted elements and change the array in place

    Login or Signup to reply.
  2. 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 from targetArr, and then the splice(2, 1) method is called on that new array. The splice() method modifies the array in place by removing one element at index 2. The splice() method returns an array containing the removed elements, so errnewArr 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 from targetArr, but this time, the splice(2, 1) method is called on the newArr array itself. The splice() method modifies the array in place, just like before, but since newArr is a separate array from targetArr, the modification doesn’t affect the original targetArr array. The element "my" is removed from newArr, 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 by Array.from(), while in Code 2, the splice() method is called on a separate array (newArr) created by Array.from().

    Login or Signup to reply.
  3. One is the target and the other is the return

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search