It may not make sense for the index of the bound element associated with the call for splicing

I found a great function to move elements in an array to different positions:

function eleMove1( arr, from, to ) {
  arr.splice( to, 0, arr.splice( from, 1 )[ 0 ] );
}

var arr = [ 'a', 'b', 'c', 'd', 'e' ];
eleMove1( arr, 3, 0 );
console.log ( 'eleMove1: ' + arr ); // eleMove1: d,a,b,c,e
console.log ( arr ); // ["d", "a", "b", "c", "e"]
console.log ( '\n ' );

/*
*/

function eleMove2( arr, from, to ) {
  arr.splice( to, 0, arr.splice( from, 1 ) );
}

var arr = [ 'a', 'b', 'c', 'd', 'e' ];
eleMove2( arr, 3, 0 );
console.log ( 'eleMove2: ' + arr ); // eleMove2: d,a,b,c,e
console.log ( arr ); // [["d"], "a", "b", "c", "e"]
console.log ( '\n ' );

But since I'm just starting out with JS, I am puzzled by the relevance of [ 0 ] );the splicing instruction part . The convention leads me to think that it refers to the first indexed element of the array. But which array? Of course, arr did not pass the function, and, of course, not the func arg array, since the original function that I removed from it did not actually pass arr as one of the func arguments:

Move an array element from one array position to another

It seems to hang from the end of the second splicing call to arr, but I still can't figure out why and why.

arr, -, . , ?

+4
2

[0] . .

function eleMove1( arr, from, to ) {
  arr.splice( to, 0, arr.splice( from, 1 )[ 0 ] );
}

.

function eleMove1( arr, from, to ) {
  deletedItemsArray = arr.splice( from, 1 );
  itemYouDeleted = deletedItemsArray[0];

  arr.splice( to, 0, itemYouDeleted);
}

, splice arr , . arr.splice, itemYouDeleted to

+4

, .

orig:    console.log ( arr ); // ["d", "a", "b", "c", "e"]
changed: console.log ( arr ); // [["d"], "a", "b", "c", "e"]
                                  ^^^^^

[0] , splice, , , .

+1

Source: https://habr.com/ru/post/1671189/


All Articles