Ternary operator with multiple operations

前端 未结 3 1615
星月不相逢
星月不相逢 2021-01-24 02:11

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) {
        dwellin         


        
相关标签:
3条回答
  • 2021-01-24 02:22

    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
    })();
    
    0 讨论(0)
  • 2021-01-24 02:36

    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

    0 讨论(0)
  • 2021-01-24 02:45

    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 = "");
    
    0 讨论(0)
提交回复
热议问题