简体   繁体   中英

How is an array organised after being spliced?

There is an array :

var tab = ["a","b","c","d"];
tab.splice(0,2);

What is the beginning index of the array after it has been spliced ? And how to know it ?

it's always 0. Even you splice, set null, undefined, etc....

I mean that if you set something such as tab[0] = null or tab[0] = undefined, the length of array is unchange, also the index. The length only change when you splice, remove item in array. Example :

 var array = [1,2,3,4,5,6,7,8];
 console.log('Array length: %s, and index 0 value : %s ',array.length, array[0] );    //should be 8 and 1
 array[0] = undefined;
 console.log('Array length: %s, and index 0 value : %s ',array.length, array[0] );    //should be 8 and undefined
 array[0] = null;
 console.log('Array length: %s, and index 0 value : %s ',array.length, array[0] );    //should be 8 and null;

now add splice:

     var array = [1,2,3,4,5,6,7,8];
     console.log('Array length: %s, and index 0 value : %s ',array.length, array[0] );    //should be 8 and 1
     var arraySpliceLength = 2;
     array.splice(0,arraySpliceLength);
     console.log('Array length: %s, and index 0 value : %s ',array.length, array[0] );    //should be 6 and 3

The length changed, but the start index still at 0, and value = array[array.length - arraySpliceLength] = 2

After splicing an input array it returns new array that starts also wint index = 0.

You can check it ie with for loop:

var output = tab.splice(0,2);
for (var i = 0; i < output.length; i++) {
  console.log(i, output[i]);
}

Use indexOf method to see result.

var tab = ["a","b","c","d"];
tab.splice(0,2);
console.log(tab);
console.log(tab.indexOf("c")); 

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM