简体   繁体   English

拼接不会改变数组的长度

[英]splice doesn't change the length of the array

JavaScript array.splice alters the length of an array. JavaScript array.splice更改数组的长度。 But the following code always seems to pull the first 10 elements of the array without change it's length. 但是下面的代码似乎总是在不更改数组长度的情况下拉取数组的前10个元素。 This throws it into an infinite loop. 这使其陷入无限循环。 What's wrong? 怎么了?

files = ['a','b','c',....]; // 100 elements
while( files.length ){
    files = files.splice( 0, 10 );
    console.log( files );
}

Problem is with you assigment.Just remove it because splice alter the array in place.and it return the removed elements that you are assigning back to array 问题出在您的分配上,只需将其删除即可,因为splice会在适当的位置更改数组,并且会将您分配的已删除元素返回给数组

 files = ['a','b','c','a1','b1','c1','a2','b2','c2','a3','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c']; // 100 elements while( files.length ){ files.splice( 0, 10 ); console.log( files ); } 

The issue is splice return an array containing the deleted elements and then you again assign that to files . 问题是splice返回一个包含已删除元素的数组,然后再次将其分配给files Hence the files array has always 10 values and condition is never false. 因此, files数组始终具有10个值,并且条件绝不会为假。 You can just use it like: 您可以像这样使用它:

files = ['a','b','c',....]; // 100 elements
while( files.length ){
    files.splice( 0, 10 );
    console.log( files.length );
    //=> 90, 80, 70, 60, 50, 40, 30, 20, 10, 0
    // after that it will get out of this loop
}

Remember, the splice() method changes the contents of an array by removing existing elements. 记住, splice()方法通过删除现有元素来更改数组的内容。 So, if you need files for further processing then keep that values in a temporary array first and then use that temp array with splice() . 因此,如果您需要files进行进一步处理,请先将该值保存在一个临时数组中,然后将该临时数组与splice()

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

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