带有 if 语句的 Javascript while 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16228470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:48:25  来源:igfitidea点击:

Javascript while loop with if statements

javascriptif-statementwhile-loop

提问by Dolbyover

I am trying to create a while loop in Javascript. I have a an array called numbers that contains 5 numbers. I also have a variable called bigone that is set to 0. I am trying to write a while loop that has an if statement that compares each value in the array to bigone. When the number in the array slot is greater then bigone, I want to assign that number to bigone. I cant figure it out. Here is what I have so far but it wont work. Yes this is homework and NO I am not asking for the answer, just for some guidance in the right direction. Here is as far as I have gotten :

我正在尝试在 Javascript 中创建一个 while 循环。我有一个名为 numbers 的数组,其中包含 5 个数字。我还有一个名为 bigone 的变量,它设置为 0。我正在尝试编写一个 while 循环,该循环具有一个 if 语句,用于将数组中的每个值与 bigone 进行比较。当数组槽中的数字大于 bigone 时,我想将该数字分配给 bigone。我想不通。这是我到目前为止所拥有的,但它不起作用。是的,这是家庭作业,不,我不是在要求答案,只是为了一些正确方向的指导。这是我所得到的:

while ( numbers.length < 5 ) {
    if ( numbers > bigone ) {
    bigone = numbers
    }
  }

Any ideas?

有任何想法吗?

采纳答案by SimonDever

Implement a counter so you can access the values in the array.

实现一个计数器,以便您可以访问数组中的值。

var i = 0;
while(numbers.length < 5 && i < numbers.length)
{
    if(numbers[i] > bigone)
        bigone = numbers[i];

    i++;
}

This is the same loop but with for. Not sure why you are checking if there are 5 or less elements in the array but ok. This checks the length on every iteration.

这是相同的循环,但使用for. 不知道为什么要检查数组中是否有 5 个或更少的元素,但没问题。这会检查每次迭代的长度。

for(var i = 0; numbers.length < 5 && i < numbers.length; i++)
{
    if(numbers[i] > bigone)
        bigone = numbers[i];
}

A better method to just check it once is to wrap the forloop in an ifstatement like this:

仅检查一次的更好方法是将for循环包装在如下if语句中:

 if(numbers.length < 5)
 {
     for(var i = 0; i < numbers.length; i++)
     {
         if(numbers[i] > bigone)
             bigone = numbers[i];
     }
 }

回答by c.P.u1

I presume you are trying to find the largest number in the array. Another way to do this is to use the forEach method, which takes a callback function as an argument. The callback is executed once for each element of the array.

我假设您正在尝试在数组中找到最大的数字。另一种方法是使用 forEach 方法,该方法将回调函数作为参数。回调对数组的每个元素执行一次。

var numbers = [4, 12, 3, 5, 1]
var big  = 0;
numbers.forEach(function(number) { if(number > big) big = number; });
console.log(big); //Prints 12

More on Array.forEach

更多关于 Array.forEach