Ternary operator with multiple operations

2019-02-27 22:07发布

Can I use a ternary operator when I have more than one operation to perform per case?

For example can I use it here?:

    if (dwelling) {
        dwelling = dwelling[0].nodeValue;      //first operation
        letterDwelling = dwelling[0].toUpperCase(); //second operation
 } else {
        dwelling = "";
        letterDwelling = "";
}

I've only used this syntax which allows one subsequent operation:

dwelling = dwelling ? dwelling[0].nodeValue : "";

3条回答
甜甜的少女心
2楼-- · 2019-02-27 22:24

Although i highly advice against it for the sake of readability and extensibility you could:

dwelling ? (dwelling = dwelling[0].nodeValue, letterDwelling=dwelling[0].toUpperCase()) : (dwelling = letterDwelling = "");
查看更多
smile是对你的礼貌
3楼-- · 2019-02-27 22:31

To avoid the side effects using the comma-notation you could use self-invoking functions instead which can handle your code:

(foo == bar) ? doSomething() : (function(){
    // here you can write all your code
    // and even return something useful
})();
查看更多
我命由我不由天
4楼-- · 2019-02-27 22:32

Yes, see: Conditional (ternary) Operator

var dwelling = true;
(dwelling) ? (
    dwelling = 'a',      //first operation
    letterDwelling = 'a' //second operation
) : (
    dwelling = 'b',
    letterDwelling = 'b'
);
alert(dwelling);

jsfiddle example

查看更多
登录 后发表回答