简体   繁体   English

三元运算符如何调用函数?

[英]How ternary operator calls a function?

Given following code:给出以下代码:

 const letters = ['a', 'b', 'c']; foo = ((list, letter) => { if (list.includes(letter)) { return true; } return false; })(letters, 'c') ? 'letter in list' : 'letter not in list'; console.log(foo);

Output will be:输出将是:

letter in list

How does ternary operator work in this example?在这个例子中三元运算符是如何工作的? Does it call foo with letters and c as parameters?它是否使用lettersc作为参数调用 foo ? How does it know to call this function?它怎么知道调用这个函数?

You can split up the expression in several parts, and look at them individually:您可以将表达式拆分为几个部分,然后分别查看:

foo = (
    (
        // Create an arrow function
        (list, letter) => {
            if (list.includes(letter)) {
                return true;
            }
            return false;
        }
    )
    // call the function
    (letters, 'c')
) /* ternary operator on call result */ ? 'letter in list' : 'letter not in list';

If you're unsure, you can usually replace expressions with variables to make it more clear:如果您不确定,通常可以用变量替换表达式以使其更清楚:

const func = (list, letter) => {
    if (list.includes(letter)) {
        return true;
    }
    return false;
};
const callResult = func(letters, 'c');
const foo = callResult ? 'letter in list' : 'letter not in list';

Most people would even say it should've used several variables anyway for readability.大多数人甚至会说它应该使用几个变量来提高可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM