【问题标题】:Possibility to declare variable from function in IF statement?可以在 IF 语句中从函数声明变量吗?
【发布时间】:2019-03-24 19:55:58
【问题描述】:

我又回来了。我有一个小问题,我可以在函数的 IF 条件中声明一个变量,并在语句本身中使用它。

好吧,我很想知道是否有办法在 IF 语句的条件中声明一个变量,并在语句中进一步使用它,如下所示:

function SomeFunc() {return true}
if (let n = SomeFunc()) {
    console.log(n); // true
    // n is truthy
} else {
    // Would never run, because it always returns true.
    // This is just an example though, where it can return a truthy or falsy value dependent on the input context I could give it.
    console.log(n); // false (if it actually returned 'false')
    // n is falsy
}

有什么方法可以做到这一点,而不必运行该函数两次并且不让它在 IF 语句之外运行?

(虽然不是这样):

let n = SomeFunc();
if (n) { ... } else { ... }

// Or this:
if (SomeFunc()) {
    let n = SomeFunc();
} else { ... }

我想在条件中声明一个函数,以最大限度地减少行的使用并让它 - 对我来说 - 干净。我希望有一种方法可以在 IF 条件中声明变量。

提前谢谢你。 ~问

【问题讨论】:

    标签: javascript function if-statement return


    【解决方案1】:

    语法不允许letconstvar 出现在该位置。 但是您可以只定义变量(无需初始化)然后执行if:

    let n;
    if (n = SomeFunc()) {
        // n is truthy
    } else {
        // n is falsy
    }
    

    如果您想将该变量的范围限制为 if,则将其放在一个块中:

    // other code...
    {
        let n;
        if (n = SomeFunc()) {
            // n is truthy
        } else {
            // n is falsy
        }
    }
    // other code...
    

    当然,如果您的函数没有其他代码,则不需要额外的块:将应用函数的块。

    许多人会不同意您的观点,即if 条件内的分配是干净的。最佳实践是避免在某种情况下出现这种副作用,尽管对此意见不一。尽管如此,它并不需要更多的字符来写它,而且对我来说看起来更干净:

    {
        let n = SomeFunc();
        if (n) {
            // n is truthy
        } else {
            // n is falsy
        }
    }
    

    作为函数表达式

    另一种方法是使用立即调用的函数表达式,将函数的返回值作为参数提供给它:

    (n => {
        if (n) {
            // n is truthy
        } else {
            // n is falsy
        }
    })(SomeFunc());
    

    【讨论】:

    • 哦,我没想过在其中调用匿名函数。谢谢你提供这样的例子。
    【解决方案2】:

    Ternary Operator

    对于简洁的语法使用三元运算符:

    var/const/let 变量 = (条件) ? 值为真 : false 时的值

    条件周围的括号是可选的。


    演示

    /* 
    Condition: if (number is greater than 10) ?
                 return true 
               : else return false
    */
    const gTTen = number => { return (number > 10) ? true : false; }
    
    console.log(gTTen(11));
    console.log(gTTen(9));
    
    function ternary(number) {
    
      /*
      Using the previous function then store its return in a 
      variable
      */
      const tenFilter = gTTen(number);
      
      /*
      Condition: if (previous value is true AND the number is
                 less than 20) ?
                   range is 30
                   : else range is 0
      */
      let range = (tenFilter && number < 20) ? 30 : 0; 
      
      /*
      Condition: if (range = 30) ? 
                   result is (the first string)
                   : else result is (the last string)
      */               
      let result = range === 30 ? `${number} is within range` : `${number} is not within range`;
      
      return result;
    }
    
    console.log(ternary(50));
    console.log(ternary(15));

    【讨论】:

    • 如何在三元表达式的真/假部分使用声明的变量?我相信这是 OP 在编写 " 时所需要的......并在声明中进一步使用它"
    • @trincot 听起来像是 OP 需要 switch() 而没有 breaks。听起来 OP 需要简化真实代码,以避免需要这种愚蠢的行为。
    【解决方案3】:

    啊!几天前我就知道了,但没有时间回复。我可以使用仅在执行语句时覆盖的局部变量。

    这是一个例子。

    function retClone(bool) {
        return bool; // Returns same input context for example.
    }
    
    if (t = retClone(true)) {
        console.log(t); // true
        // t is truthy, because we get `true` returned.
    }
    
    if (t = retClone(false)) {
        // Wouldn't run.
        // t is falsy.
    } else {
        console.log(t); // false
    }
    

    感谢所有回复的人。 ~问

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      • 2018-07-31
      • 2014-04-12
      • 2014-08-26
      • 1970-01-01
      相关资源
      最近更新 更多