【问题标题】:Javascript: Variable as While ConditionJavascript:变量作为 While 条件
【发布时间】:2011-08-25 22:10:11
【问题描述】:

我想将 while 的条件指定为变量,例如:

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

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

【问题讨论】:

    标签: javascript variables while-loop conditional-statements


    【解决方案1】:

    做到这一点的唯一方法是使用函数。

    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);
    

    【讨论】:

    • 什么,你不想循环运行eval()? ;o) +1
    • @patrick_dw 我被诱惑了。但我决定正确地做这件事。此外,如果我向他展示 eval 解决方案,他会说“那更容易/更好,我就用它。你是什么意思 eval 不好?eval 很好!”
    • @Raynos:我在今年早些时候看到了确切的情况,但有人使用with 给出了解决方案。 OP 只用了几分钟就破解了他的代码,但他确信with 是解决方案。
    • 嗯,它有效,但我真的不明白发生了什么:S,return number === undefined || number &lt; 10; 为什么我需要这里的number === undefined 部分?
    • @CIRK 第一个电话是undefined。如果需要,您可以初始化 result = 0。但是它默认为 0 而不是 undefined 并且不能很好地处理字符串或数组。如果你不习惯像这样传递一流的函数,我可以想象这个看起来很陌生。
    猜你喜欢
    • 2021-08-13
    • 2023-03-04
    • 1970-01-01
    • 2014-08-01
    • 2018-10-02
    • 1970-01-01
    • 2017-09-11
    • 2012-02-14
    • 2016-01-13
    相关资源
    最近更新 更多