while循环在没有条件的情况下如何工作? [英] How does while loop work without a condition?

查看:90
本文介绍了while循环在没有条件的情况下如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解它正在删除 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:

false

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循环在没有条件的情况下如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆