拼接后阵列是如何组织的?

时间:2014-09-29 07:05:28

标签: javascript

有一个数组:

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

数组拼接后的起始索引是什么?怎么知道呢?

3 个答案:

答案 0 :(得分:2)

它总是0.即使你拼接,设置null,未定义等等....

我的意思是,如果你设置了tab [0] = null或tab [0] = undefined之类的东西,那么数组的长度是不变的,也就是索引。只有在拼接时才会更改长度,删除数组中的项目。 示例:

 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;

现在添加拼接:

     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

长度发生了变化,但起始索引仍为0,而value = array [array.length - arraySpliceLength] = 2

答案 1 :(得分:1)

在拼接输入数组后,它返回新的数组,该数组也开始wint index = 0。

您可以使用for循环检查它:

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

答案 2 :(得分:1)

使用indexOf方法查看结果。

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

DEMO