简体   繁体   English

javascript while循环,以正数为条件

[英]javascript while loop, positive number given as a condition

I know that in javascript a 1 evaluates as true , while a 0 evaluates as false . 我知道在javascript中1评估为true ,而0评估为false

My question is regarding the while loop in javascript, in the format as follows: 我的问题是关于javascript中的while循环,其格式如下:

while (condition) {
code block to be executed
}

If I pass a single integer as a condition for the while loop, how does the code function? 如果我将一个整数作为while循环的条件,那么代码如何工作? More specifically, here is the code I was working on before posting this question: 更具体地说,这是发布此问题之前我正在处理的代码:

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

chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);

and it seems to be working perfectly fine, returning the newArr the way I need it to by dividing the original array ( arr ) the amount of times required ( size ) and push ing that to the newArr. 它似乎工作得很好,通过将原始数组( arr )除以所需的时间量( size )并将其 送到newArr ,以我需要的方式返回newArr。

How does the condition arr.length evaluate? 条件arr.length如何评估? My assumption is that it evaluates as true as long as it is not zero, ie a nonzero number, despite it not being a comparison such as i < 2. 我的假设是,即使它不是i <2之类的比较,只要它不为零(即非零数字),它的评估结果就为true。

This exercise came from freeCodeCamp: Chunky Monkey 此练习来自freeCodeCamp:“ 矮胖的猴子”

  • Any number that is not 0 evaluates to true . 任何非0数字都将计算为true
  • 0 evaluates to false . 0计算为false

So, your code will run until arr.length is equal to 0 - it is the same as saying while (arr.length!=0) 因此,您的代码将一直运行到arr.length等于0为止-与说while (arr.length!=0)

if you're evaluating array's length property, it will be true until array is not empty ( length is not 0 ). 如果您要评估数组的length属性,则在数组不为空(length不为0)之前,它都是正确的。 When the array is empty ( length is 0) evaluation will return false. 当数组为空(长度为0)时,评估将返回false。

Yes

Yes, you are absolutely right, it evaluates as true whilst arr has a length because arr.length is > 0 so is considered true. 是的,您绝对正确,因为arr.length > 0所以当arr具有长度时,它的评估结果为true,因此认为它是正确的。 It is a neat feature of javascript however it is not that readable (as you have found) and can therefore be confusing to anyone not used to it. 它是javascript一个很好的功能,但是可读性不强(如您所见),因此可能会使任何不习惯它的人感到困惑。 However if you are coding for yourself, this is a clever little function! 但是,如果您要为自己编码,那么这是一个聪明的小功能!

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

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