首页 > 解决方案 > 如何在三元运算符中转换此代码

问题描述

我有这段代码,我使用递归来控制一些数字,而不使用 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);

标签: javascriptecmascript-6conditional-operator

解决方案


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

test(80);

推荐阅读