问题描述
我了解它正在删除 array
的前三个元素,并将它们添加到新数组中.但是函数如何继续将随后的数组块添加到新的数组变量中?
I understand that it's removing the first 3 elements of the array
and adding them to the new array. But how does the function continue to add ensuing chunks of the array to the new array variable?
while
循环如何在没有适当条件的情况下工作?
How does the while
loop work without proper conditions?
它如何与此处的 splice()
协作?
function chunkArrayInGroups(arr, size){
let newArr = [];
while(arr.length){
newArr.push(arr.splice(0, size))
}
return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
推荐答案
条件为 while(arr.length)
.当条件真实时,将运行while循环.在JavaScript中,除非满足以下条件之一,否则每个条件都是真实的:
The condition is while(arr.length)
. The while loop will run while that condition is truthy. In JavaScript every condition is truthy unless it is one of the following:
0(零)
''或"(空字符串)
空
未定义
NaN(例如1/0的结果)
NaN (e.g. the result of 1/0)
在您的情况下,当数组中包含元素时, while
循环将运行( arr.length
大于零),因为如果 arr.长度
为零,而while循环将停止执行.
In your case the while
loop will run while the array has elements in it (arr.length
is greater than zero), because if the arr.length
is zero the while loop will stop executing.
arr.splice
每次执行时都会从 arr
中删除一个元素(这会更改 arr
的长度).因此,当 arr
中没有任何元素时(由于 arr.splice
删除了所有元素), while
循环将停止.
arr.splice
on the other hand is removing one element from arr
every time it is executed (it is changing the arr
length). So when there are no elements left in the arr
(because arr.splice
removed them all) the while
loop will stop.
这篇关于while循环在没有条件的情况下如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!