简体   繁体   English

while 循环如何在没有条件的情况下工作?

[英]How does while loop work without a condition?

I understand that it's removing the first 3 elements of the array and adding them to the new array.我知道它正在删除array的前 3 个元素并将它们添加到新数组中。 But how does the function continue to add ensuing chunks of the array to the new array variable?但是该函数如何继续将随后的数组块添加到新的数组变量中呢?

How does the while loop work without proper conditions?如果没有适当的条件, while循环如何工作?

How does it work in collaboration with splice() here?它是如何与splice()协同工作的?

function chunkArrayInGroups(arr, size){
  let newArr = [];
  while(arr.length){
    newArr.push(arr.splice(0, size))
  }
  return newArr;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

Conditions in js are either "truthy" or "falsy", for numbers everything except 0 is "truthy", 0 is "falsy". js 中的条件是“真”或“假”,对于数字,除 0 外的所有内容都是“真”,0 是“假”。 That means that the loop runs until the array is empty, its length 0 and therefore falsy.这意味着循环运行直到数组为空,其长度为 0,因此为假。

 if(0) alert("never");
 if(1) alert("always");
 let i = 3;
 while(i) console.log(i--);

The while loop is gonna keep going until the original array is empty. while 循环会一直运行,直到原始数组为空。 Splice will remove the selected elements from the original array and while will continue until the last elements are removed. Splice 将从原始数组中删除所选元素,而 while 将继续直到删除最后一个元素。

Also, as the elements are removed from the original array, they are being pushed (added) to the new array此外,随着元素从原始数组中删除,它们被推送(添加)到新数组中

The condition is while(arr.length) .条件是while(arr.length) The while loop will run while that condition is truthy . while 循环将在条件为真时运行。 In JavaScript every condition is truthy unless it is one of the following:在 JavaScript 中,每个条件都是真实的,除非它是以下之一:

false错误的

0 (zero) 0(零)

'' or "" (empty string) '' 或 ""(空字符串)

null空值

undefined不明确的

NaN (eg the result of 1/0) NaN(例如 1/0 的结果)

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.在您的情况下, while循环将在数组中有元素时运行( arr.length大于零),因为如果arr.length为零,while 循环将停止执行。

arr.splice on the other hand is removing one element from arr every time it is executed (it is changing the arr length).另一方面, arr.splice每次执行时都会从arr删除一个元素(它正在改变arr长度)。 So when there are no elements left in the arr (because arr.splice removed them all) the while loop will stop.因此,当arr中没有元素时(因为arr.splice将它们全部删除), while循环将停止。

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

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