Javascript:变量作为 While 条件

发布于 2024-11-07 12:18:54 字数 192 浏览 0 评论 0原文

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

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

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

I would like to specify the while's condition as a variable, something like:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゃ懵逼小萝莉 2024-11-14 12:18:54

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

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文