如何在三元运算的结果上执行多个函数

How to I execute multiple functions on the result of a ternary operation?

本文关键字:结果 执行 函数 运算 三元      更新时间:2023-09-26

我有一个if/else语句,如果它的计算结果为true,则会导致调用两个函数。

if (isTrue) {
    functionOne();
    functionTwo();
} 
else {
    functionThree();
}

我希望能够将其放在这样的三元语句中:

isTrue ? (functionOne(), functionTwo()) : functionThree();

这可能吗?

你的例子确实是有效的javascript。您可以使用逗号分隔表达式,并将其括在单个语句中,并用括号表示三元。

var functionOne   = function() { console.log(1); }
var functionTwo   = function() { console.log(2); }
var functionThree = function() { console.log(3); }
var isTrue = true;
isTrue ? (functionOne(), functionTwo()) : functionThree();
// 1
// 2
isTrue = false;
isTrue ? (functionOne(), functionTwo()) : functionThree();
// 3

但是,这是不可取的。带有if语句的版本更加清晰易读,并且执行速度也一样快。在我见过或使用过的大多数代码库中,逗号运算符从未以这种方式使用因为它比有用更令人困惑。

仅仅因为你可以,并不意味着你应该这样做。

你总是可以将任何内容包装到一个匿名函数中并立即调用它,即所谓的立即调用函数表达式 (IIFE),如下所示

isTrue ? (function() { functionOne(); functionTwo() })() : functionThree();

但正如你所看到的,它看起来非常糟糕,并且是对三元运算符的非常糟糕的滥用(它不会返回任何有用的东西),所以我真的建议不要这样做。

出于某种原因,对我有用的是将这两个函数作为数组中的对象返回。否则,三元运算符只返回最后一个函数。请参阅以下示例:

isTrue ? [fucnctionOne(), functionTwo()] : functionThree()

当然,您可以将语句括在括号*()*中,并用逗号*分隔它们,*

condition ? (doThis, andThis) : (doThat, andThat)

在您的情况下 (OP):

isTrue ? (functionOne(), functionTwo()) : functionThree();