Javascript:变量作为 While 条件

标签 javascript variables while-loop conditional-statements

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

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

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

最佳答案

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

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

关于Javascript:变量作为 While 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6008981/

相关文章:

用于具有特定字符顺序的强密码的 Javascript 正则表达式

function - Julia 中局部变量不受支持的 `const` 声明

php - 解析 YML 时将变量从 PHP 传递到 YML 文件

c - 为什么输出是 36 而不是 24?

c - C语言中n个数相加

javascript - HTML5 和 JavaScript 中的视频音量 slider

javascript - 如何从数组创建一个集合并删除 JavaScript 中的原始项目

php - 将 php sql 查询 while 循环转换为 for 循环

javascript - 使用 windows.location.replace 重定向到 ItemID

javascript - 带有 Javascript 变量的 JSON