简体   繁体   English

Array.splice()是否可以通过在数组的最后一个元素之外的索引处添加元素来创建稀疏数组?

[英]Can Array.splice() be used to create a sparse array by adding an element at an index beyond the last element of the array?

可以通过在数组的最后一个元素之外的索引处添加一个元素来使用Array.splice()创建稀疏数组吗?”我需Array.splice()因为在某些情况下我只想推送到该数组上,但是在其他情况下,需要拼接到数组中,但是尝试使用拼接使数组稀疏是行不通的,尽管在我的特定情况下,我能够实现一些代码来测试是否使用拼接,或者只是在超出索引的位置分配数组元素数组的长度。

No. The ECMAScript specification does not allow a relative start position greater than the array length. 否。ECMAScript规范不允许相对起始位置大于数组长度。 From ES2015 on Array.prototype.splice , step 7: ES2015的Array.prototype.splice ,执行步骤7:

  1. ...let actualStart be min( relativeStart , len ). ...让actualStart为min( relativeStartlen )。

The variable actualStart is what's actually used for the splice algorithm. 变量actualStart是实际用于splice算法的变量。 It's produced by the minimum of relativeStart (the first argument to the function) and len (the length of the array). 它是由relativeStart (函数的第一个参数)和len (数组的length )的最小值产生的。 If len is less than relativeStart , then the splice operation will use len instead the actual argument provided. 如果len小于relativeStart ,则splice操作将使用len代替提供的实际参数。

In practical terms, this means that you can only append values onto the end of arrays. 实际上,这意味着您只能将值附加到数组的末尾。 You cannot use splice to position a new element past the length index. 您不能使用splice将新元素放置在length索引之后。

It should be noted the length of the array is not necessarily the index of the last item in the array plus 1. It can be greater. 应当注意,数组的长度不一定是数组中最后一项的索引加1。它可以更大。

Then, you can't use splice to insert elements beyond the length of the array, but if you make sure the length is large enough, you can insert beyond the last index plus 1. 然后,您不能使用splice插入超出数组长度的元素,但是如果确保长度足够大,则可以插入超出最后一个索引加1的元素。

var arrSplice = ['what', 'ever'];
arrSplice.length = 10; // Increase the capacity
arrSplice.splice(10, 0, 'foobar'); // Now you can insert items sparsely
console.log(arrSplice.length); // 10
console.log(arrSplice[arrSplice.length - 1]); // foobar

Array.splice() cannot be used to create sparse arrays. Array.splice() 不能用于创建稀疏数组。 Instead, if the index argument passed to Array.splice() is beyond the length of the array, it seems that the element just gets appended to the array as if Array.push() had been used. 相反,如果传递给Array.splice()的index参数超出了数组的长度,则似乎该元素只是被追加到数组,就像使用了Array.push()一样。

/* How you might normally create a sparse array */
var arrNoSplice = ['foo', 'bar'];
arrNoSplice[10] = 'baz';
console.log(arrNoSplice.length); // 11

/* Demonstrates that you cannot use splice to create a sparse array */
var arrSplice = ['what', 'ever'];
arrSplice.splice(10, 0, 'foobar');
console.log(arrSplice.length); // 3
console.log(arrSplice[arrSplice.length - 1]); // foobar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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