简体   繁体   English

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

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

i have this code where i am using recursion to console some numbers, without using for loop.我有这段代码,我使用递归来控制一些数字,而不使用 for 循环。

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

test(80);

is there any way to solve this in one line with ternary operator without using external function like this:有没有什么方法可以在不使用这样的外部函数的情况下用三元运算符在一行中解决这个问题:

let counter = 0;

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

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

test(80);

Although I wouldn't recommend it, this would work iff function proba() accepts an additional argument.虽然我不推荐它,但如果函数proba()接受额外的参数,这将起作用。 console.log(var) returns the value of var , in case your c is just a shorthand for console . console.log(var)返回的值var ,如果你c仅仅是一个速记console

But really, I don't see any recursion in your code.但实际上,我在您的代码中没有看到任何递归。 The undefined proba() and test() function seem independent of each other.未定义的proba()test()函数似乎彼此独立。

let counter = 0;

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

test(80);

This is an approach without using a global variable.这是一种不使用全局变量的方法。

 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