简体   繁体   English

Javascript - 有条件地选择 while 循环的条件

[英]Javascript - Conditionally selecting the condition of a while loop

I need to fill an array with randomly selected elements until the array reaches an appointed length .我需要用随机选择的元素填充数组,直到数组达到指定的长度 The length of that array must be equal to the smallest of two lengths.该数组的长度必须等于两个长度中的最小值。 We'll call them length_1 and length_2 .我们将它们length_1length_2 So if length_1 < length_2 , then use length_1 , otherwise, use length_2 .因此,如果length_1 < length_2 ,则使用length_1 ,否则使用length_2 Note that both lengths are constant so the statement length_1 < length_2 will always give the same Boolean value.请注意,两个长度都是常数,因此语句length_1 < length_2将始终给出相同的布尔值。

The method I came up with to deal with that situation is to create a while loop which, at each turn, adds a new randomly selected element to the array.我想出的处理这种情况的方法是创建一个while 循环,它在每一轮都会向数组中添加一个新的随机选择的元素。 It goes like this:它是这样的:

while (
length_1 < length_2
  ? array.length < length_1
  : array.length < length_2
  ) {
    // Add a new randomly selected element to the array
     };

Is this a valid way to it?这是一种有效的方法吗? Is there a more concise way to go about it?有没有更简洁的方法来解决它?

You could get the minimum in advance for a looping condition.您可以提前获得循环条件的最小值。

const
    length = Math.min(length_1, length_2);

while (array.length < length) {
    // ...
}

I try to avoid while loops.我尽量避免while循环。 They are prone to get into an endless loop.他们很容易陷入无限循环。

const length = Math.min(length_1, length_2);

for(let i = 0; i < length; i+=1) {
  //...
}

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

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