How does while loop work without a condition?

旧街凉风 提交于 2021-02-05 09:17:45

问题


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?

How does the while loop work without proper conditions?

How does it work in collaboration with splice() here?

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

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

回答1:


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 (zero)

'' or "" (empty string)

null

undefined

NaN (e.g. the result of 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.

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.




回答2:


Conditions in js are either "truthy" or "falsy", for numbers everything except 0 is "truthy", 0 is "falsy". That means that the loop runs until the array is empty, its length 0 and therefore falsy.

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



回答3:


The while loop is gonna keep going until the original array is empty. Splice will remove the selected elements from the original array and while will continue until the last elements are removed.

Also, as the elements are removed from the original array, they are being pushed (added) to the new array



来源:https://stackoverflow.com/questions/52558602/how-does-while-loop-work-without-a-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!