开发者

Javascript: Variable as While Condition

开发者 https://www.devze.com 2023-03-05 20:23 出处:网络
I would like to specify the while\'s condition开发者_JS百科 as a variable, something like: function doWhile(condition){

I would like to specify the while's condition开发者_JS百科 as a variable, something like:

function doWhile(condition){
    while(condition){
       number++;
    }
    alert(number);
}

var number = 1;
doWhile(number < 10);


The only way to do this is using functions.

function doWhile(condition, action, undefined) {
    var current = undefined;
    // call your condition with the current value
    while(condition(current)) {
        // do something with the current value then update it
        current = action(current);
    }
    return result;
}

var number = doWhile(function condition(number) {
    // if the current value has no value yet continue
    // if the current value is less than 10
    return number === undefined || number < 10;
}, function action(number) {
    // if the number has no value set it to 0
    if (number === undefined) {
         number = 0;
    }
    // increase it
    return ++number;
});
console.log(number);
0

精彩评论

暂无评论...
验证码 换一张
取 消