简体   繁体   English

函数中的三元运算符

[英]ternary operator in a function

I'm new to ternary operators. 我是三元运算符的新手。 I have the following function. 我有以下功能。 I'm trying to understand what's going on: 我试图了解正在发生的事情:

function toProperHex(hex) {
    hex = hex.toLowerCase();
    return hex ? hex != 'ffffff' ? '#' + hex : '#eee' : '#000';
}

I know that whatever is before the ? 我知道那之前是什么? is the condition and what comes after is the value that the variable becomes if the condition is true, and after the colon, will be what the cariable becomes if the condition is not true. 是条件,其后是条件为真时变量变为的值,冒号之后为条件不成立时可变量变为的值。 Now there are two conditions apparently and three possible outcomes. 现在显然有两个条件和三个可能的结果。 Is this an if / else if statement with a Ternary structure. 这是具有三元结构的if / else if语句。 Clarification would be greatly appreciated. 澄清将不胜感激。

Thanks! 谢谢!

This is two ternary operators on one line. 这是一行上的两个三元运算符。 It's equivalent to this: 等效于:

if(hex) {
    if(hex != 'ffffff') {
        return '#' + hex;
    } else {
        return '#eee';
    }
} else {
    return '#000';
}

I think two ternaries on one line is a bad idea, makes them hard to read. 我认为在同一行上的两个三元组是个坏主意,使它们难以阅读。 You can basically divide it up like this 你基本上可以这样划分

return hex ? (hex != 'ffffff' ? '#' + hex : '#eee') : '#000';

The parentheses help show the inner ternary. 括号有助于显示内部三元。

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

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