繁体   English   中英

在循环中使用变量作为大于/小于运算符

[英]Using variables as greater than / less than operators in a loop

最近,我一直在处理一些紧凑的代码,并且我试图获得一个尽可能小的非常奇怪的 for 循环。

function test (start, comparison, end, increment) {
    for (x = star; x comparison end; x += increment) {
        console.log("e");
    }
}
test(1, "<", 3, 1);

//Expected theoretically
// for (x = 1; x < 3; x += 1) {
//  console.log("e");
//}

我知道我可以让循环使用,例如 if / else 语句,但我正在寻找一种更小的方法来做到这一点,因为这会使代码大两倍(对于更长的“for 循环”)。

function test (start, value, end, increment) {
  if (value > 0) {
    //Loop 1
  } else {
    //Loop 2
  }
}

所以是的,有没有办法做到这一点? 还是我坚持只用 1 个不同的字符制作两个不同的循环? 提前致谢

您可以使用函数而不是字符串,因为可以在不使用eval情况下调用该函数,这是不可取的。

 function test (start, comparison, end, increment) { for (var x = start; comparison(x, end); x += increment) { console.log(x); } } const isSmaller = (a, b) => a < b; test(1, isSmaller, 3, 1);

暂无
暂无

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

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