Reputation: 454
JavaScript array.splice alters the length of an array. But the following code always seems to pull the first 10 elements of the array without change it's length. 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 );
}
Upvotes: 1
Views: 2123
Reputation: 73906
The issue is splice
return an array containing the deleted elements and then you again assign that to files
. Hence the files
array has always 10 values and condition is never false. 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. 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()
.
Upvotes: 1
Reputation: 7368
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
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 );
}
Upvotes: 1