Concatenate string with ternary operator in javascript

前端 未结 2 747
再見小時候
再見小時候 2020-12-11 21:27

Its being annoying

Following code :

var arrays = [1,2,3];
alert(\'Array has \' + (arrays.length > 0) ? \'multiple\':\'single\' +         


        
相关标签:
2条回答
  • 2020-12-11 21:42

    Your first example is parsed this way

    alert(('Array has ' + (arrays.length > 0)) ? 'multiple':('single' + ' value'));
    

    given the operator precedence of + is much higher than that of ?:.

    0 讨论(0)
  • 2020-12-11 21:52

    Both snippets are syntactically correct, but they differ because of operator precedence. The ternary operator has lower precedence than +.

    In the first snippet:

    var arrays = [1,2,3];
    alert('Array has ' + (arrays.length > 0) ? 'multiple':'single' + ' value');
    

    Javascript evaluates the first part 'Array has ' + (arrays.length > 0), which gives the string 'Array has true'. For conditional purposes, the nonempty string is the same as true (usually called a truthy value). Because the first operand in the ternary operator is truthy, the value of the whole expression will be the value of the expression 'multiple', that's between the ? and the :.

    When you add the parameters in the second snippet, you make the ternary operator take only (arrays.length > 0) as its condition. That's why the code works as expected.

    0 讨论(0)
提交回复
热议问题