【问题标题】:how to find even numbers?如何找到偶数?
【发布时间】:2021-05-22 09:43:23
【问题描述】:

我试图找到从 0 到 100 的偶数,但它不起作用。即使它没有显示任何错误。谁能帮我弄清楚?

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>        
var x = 1;
        while (x <= 100) {
            if (x % 2 == 0) {
                console.log(x);
            } else {
                break;
            }
            x++;
        }
    </script>
</body>

</html>

【问题讨论】:

  • 一旦x % 2 == 0 为假,它就会从您的while 循环中中断,x = 1 就是这种情况。

标签: javascript while-loop


【解决方案1】:
function printEven() {
   for (let i = 1; i < 100; i++) {
      if(i % 2 === 0) {
        console.log(i);
      }
   }
}

【讨论】:

  • 没问题!如果您能将其标记为有用并批准答案,我将不胜感激(:
  • 大声笑我不认为你希望他标记答案
【解决方案2】:
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>
    var x = 1;
        while (x <= 100) {
            if (x % 2 == 0) {
                console.log(x);
            } else {
                break;
            }
            x++;
        }
    </script>
</body>

</html>

它在第一轮结束后停止,因为“if (x % 2 == 0)”不匹配,else 是一个“break”

【讨论】:

    【解决方案3】:

    它像 ivar 所说的那样打破了你的 while 循环

        while (x <= 100) {
            if (x % 2 == 0) {
                console.log(x);
            }
            x++;
        }
    

    【讨论】:

      【解决方案4】:

      for(let x =0; x<=100; x+=2){
      console.log(x);
      }

      我不会检查偶数。从 0 开始并在每次迭代中添加 2 会更容易。

      【讨论】:

        【解决方案5】:

        这里是一个班轮:

        Array(50).fill().map((_, i) => i*2+2).forEach((v) => console.log(v))
        
        // Alternatives
        console.log(  Array(50).fill().map((_, i) => i*2+2)  )
        console.log(  [...Array(50).keys()].map(i => i*2+2)  )
        console.log(  [...Array(50)].map((_, i) => i*2+2)    )
        console.log(  Array.from(Array(50), (_, i) => i*2+2) )

        jk

        【讨论】:

        • 我喜欢你的方法
        • Array.from({ length: 50 }, (_, index) =&gt; (index + 1) * 2).forEach((val) =&gt; console.log(val)) 将省略 fill
        猜你喜欢
        • 2013-03-05
        • 1970-01-01
        • 2016-01-16
        • 1970-01-01
        • 2022-10-06
        • 2012-09-02
        • 2018-08-25
        • 2016-03-21
        • 1970-01-01
        相关资源
        最近更新 更多