[英]Is JavaScript Conditional Operator better method for this if/else statement?
I am trying to see if I can reduce the code below with less JavaScript.我想看看我是否可以用更少的 JavaScript 减少下面的代码。 When the user select Even dropdown option the only differences between that and the else statement is "i = 0" and "i % 2 === 0"
当用户选择 Even 下拉选项时,它与 else 语句之间的唯一区别是“i = 0”和“i % 2 === 0”
any recommendations?有什么建议吗? Maybe conditional operator would be best method?
也许条件运算符是最好的方法? thank you
谢谢你
if (this.selection == "even") {
for (let i = 0; i <= number; i++) {
if (i % 2 === 0)
this.results.push(i + "\n");
}
} else {
for (let i = 1; i <= number; i++) {
if (i % 2 !== 0)
this.results.push(i + "\n");
}
}
Use this.selection
to determine the starting number, then increment by 2 inside the loop instead of i++
, so you don't have to check i % 2
.使用
this.selection
来确定起始编号,然后在循环内增加 2 而不是i++
,因此您不必检查i % 2
。
const startAt = this.selection == "even" ? 0 : 1;
for (let i = startAt; i <= number; i += 2) {
this.results.push(i + "\n");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.