简体   繁体   English

将for循环条件分配给变量

[英]Assign for-loop condition to a variable

Is there any way to assign a variable as the conditional operator in a for loop in Javascript? 有没有办法在Javascript中的for循环中将变量指定为条件运算符?

For example, take this for loop: 例如,将此for循环:

for(var i = 0, j = 5; i < 10; i++, j++) {
    console.log(i + ", " + j);
}

I want to be able to set the i < 10 part as a variable. 我希望能够将i < 10部分设置为变量。 I might want the for loop to run until j < 8 instead of i < 10 . 我可能希望for循环运行直到j < 8而不是i < 10 The way I am currently doing it is using an if statement and then using two different for loops with the exact same code except for the conditional, and I just wanted to know if a more efficient way was possible. 我目前正在这样做的方式是使用if语句,然后使用两个不同的for循环和完全相同的代码,除了条件,我只想知道是否有更高效的方法。 Thanks! 谢谢!

Use a function in the for loop and reassign it to whatever you want. 在for循环中使用一个函数并将其重新分配给您想要的任何内容。

var predicate = function(i, j) { return i < 10; }

for(var i = 0, j = 5; predicate(i, j); i++, j++) {
    console.log(i + ", " + j);
    if (i === 5) { // Dummy condition
        predicate = function(i, j) { return j < 8; };
    }
}

The advantage is that you can completely change the logic if you need to. 优点是,如果需要,您可以完全更改逻辑。

You can replace the 10 with a variable. 您可以用变量替换10 You cannot replace the operator ( < ) with a variable. 您不能用变量替换运算符< )。

You can replace the entire expression with a function though, and that function can be stored in a variable. 您可以使用函数替换整个表达式,并且该函数可以存储在变量中。

var data = ["a", "b", "c"];

function loop(callback) {
    for (var i = 0; callback(i); i++) {
        console.log(data[i]);
    }
}

loop(function (i) {
    return (i < 10);
});

loop(function (i) {
    return (i < 8);
});

Sure, did you try just sticking variables in there : 当然,你是否试着在那里插入变量:

var total = true==true ? 8 : 10,
    i     = 0,
    j     = 5,
    what  = true==false ? i : j;

for(; what < total; i++, j++) {
    console.log(i + ", " + j);
}

I guess you can create a random function for this? 你可以为此创建一个随机函数?

function countdown = (function(){
   var i =0, j = 5;
   return function(){
       ++i; ++j;
       return i < 10; // or j < 8
   }
})();

while(countdown()) {
    console.log('counting');
}

The only problem with that is that you cannot access i and j in the scope of your loop. 唯一的问题是你不能在你的循环范围内访问ij

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

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