繁体   English   中英

我如何在三元运算符中转换此代码

[英]How can i transform this code in ternary operator

我有这段代码,我使用递归来控制一些数字,而不使用 for 循环。

let counter = 0;
function test() {
    if(counter <= 50) {
        c.log(counter);
        ++counter;
        test();
    } else {
       return;
    }
}

test(80);

有没有什么方法可以在不使用这样的外部函数的情况下用三元运算符在一行中解决这个问题:

let counter = 0;

function doSomething() {
    c.log(counter);
    ++counter;
    test();
}

function test() {
    counter <= 50 ? doSomething() : null;
}

test(80);

虽然我不推荐它,但如果函数proba()接受额外的参数,这将起作用。 console.log(var)返回的值var ,如果你c仅仅是一个速记console

但实际上,我在您的代码中没有看到任何递归。 未定义的proba()test()函数似乎彼此独立。

let counter = 0;

function test(n) {
    counter <= 50 ? proba(c.log(counter++)) : null;
}

test(80);

这是一种不使用全局变量的方法。

 function test(n) { if (n < 0) return; // exit condition test(n - 1); // recursive call console.log(n); // deferred output } test(50);

function test() {
    counter <= 50 ? (c.log(counter), ++counter, test()) : null;
}

test(80);

暂无
暂无

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

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