【问题标题】:How can i transform this code in ternary operator如何在三元运算符中转换此代码
【发布时间】:2020-12-18 16:16:17
【问题描述】:

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

【问题讨论】:

  • 你对n做了什么吗?
  • 您为什么要这样做?你的代码是可读的,你为什么要弄乱它?
  • 顺便说一句,如果以后没有代码,else return; 是多余的。
  • 我很好奇三元运算符是否有可能的答案。
  • 请添加描述您想要达到的目标。你首先有一个带有全局计数器的函数,然后你调用这个函数一次,然后调用proba。没有递归,只是其他不清楚的东西。第二个代码也没有递归。

标签: javascript ecmascript-6 conditional-operator


【解决方案1】:

虽然我不推荐它,但如果函数 proba() 接受附加参数,这将起作用。 console.log(var) 返回 var 的值,以防您的 c 只是 console 的简写。

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

let counter = 0;

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

test(80);

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 有了这个速记,test(n - 1) 和 console.log 是 else 块吗? console.log(n) 如何等待并在最后打印结果?你能解释一下吗
    • 它只需要给定的顺序。也许只有三个电话的例子更容易理解。首先,使用test(3),它接受检查。它是false,接下来是test(2) 的下一个调用(没有控制台),然后另一个检查是false,它继续使用test(1) 等,直到test(-1) 然后递归结束。它遵循console.log(2) 这个函数结束。它遵循console.log(1) 这个函数结束。等等直到console.log(3)
    • 感谢您的解释。我明白了,但我不知道如何保存整个时间 n 以及在 console.log 连续触发五次之后
    【解决方案3】:
    function test() {
        counter <= 50 ? (c.log(counter), ++counter, test()) : null;
    }
    
    test(80);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-08
      • 2021-11-16
      • 2020-01-30
      • 1970-01-01
      • 2015-02-07
      • 2020-06-05
      • 2017-01-01
      • 1970-01-01
      相关资源
      最近更新 更多