简体   繁体   English

我在这个循环中做错了什么? js

[英]What am I doing wrong in this loop? js

I am trying to solve this loop but I can't solve it我正在尝试解决这个循环,但我无法解决

You must create a function called loopDePares that receives a number as a parameter and loops from 0 to 100, displaying each loop number on the console.您必须创建一个名为 loopDePares 的 function,它接收一个数字作为参数并从 0 循环到 100,在控制台上显示每个循环编号。 If the number of the iteration, added to the number passed by parameter, is even, it will show in the console “The number x is even”.如果迭代次数加上参数传递的次数是偶数,那么控制台会显示“The number x is even”。

what i did was this我做的是这个

function loopDePartes(numero){
  for (let i = 0; i <numero; i++){
    console.log(i+numero % 2 ? i : "x")
  }
}

loopDePartes(10)

You had one math error, and one comparison error.你有一个数学错误和一个比较错误。

i+numero needs to be wrapped in parens so it take precedence over the modulus operator. i+numero需要用括号括起来,因此它优先于模运算符。

Your ternary was checking the truthiness of the output of that math, instead of checking whether it was even or odd.您的三元组正在检查该数学的 output 的真实性,而不是检查它是偶数还是奇数。

Both are corrected below:两者都在下面更正:

 function loopDePartes(numero){ for (let i = 0; i < 100; i++){ console.log((i+numero) % 2 == 1? i: `The number ${i+numero} is even` ) } } loopDePartes(10)

(Actually, the more I reread your question the less I understand what is the expected output; I think this is what you're looking for but I may have misinterpreted what you meant by "display the loop number", and what "x" is supposed to be in "The number x is even".) (实际上,我越是重读您的问题,就越不了解预期的 output 是什么;我认为这就是您要查找的内容,但我可能误解了您所说的“显示循环编号”和“x”的含义应该在“数字 x 是偶数”中。)

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

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