简体   繁体   中英

How is this JavaScript ternary operator working

Happy thanksgiving all:

I've been racking my brain around this one for a half hour and can't quite get where the conditionals are kicking in. I think I've got it down, but just wanted to run it by the pros.

(i%3)?(i%5)?i:'Buzz':(i%5)?'Fizz':'FizzBuzz'

It breaks down to the following:

    if ((i%3) == false) {
        if ((i%5) == false) {
            console.log("FizzBuzz");
        } else {
            console.log('Fizz');
        }
    } else {
        if ((i%5) == false) {
            console.log("Buzz");
        } else {
            console.log(i);
        }
    }

And I assume the ternary operator is grouped as per the following (I'm use to seeing ternary operators in the typical result ? a : b fashion, so the extra result and conditionals is throwing me)

(i%3)?
    //if the condition is not a multiple of 3
    //check if it is a multiple of 5
    //if it isn't, log the number
    //otherwise log "Buzz" 
    (i%5)?i:'Buzz'
    //if the condition is a multiple of 3
    //check if it is a multiple of 5
    :(i%5)?
        //if it is log "Fizz", 
        //otherwise i is a multiple of 3 & 5 -
        //log "FizzBuzz"
        'Fizz':'FizzBuzz

I really appreciate any quantifying posts and/or clarification. Thanks again.

The ternary operator has right-to-left associativity , which means that the expression is the same as

(i%3) ? ((i%5) ? i : 'Buzz') : ((i%5) ? 'Fizz' : 'FizzBuzz')

Or it breaks down in the following manner

1st ? ( 2nd ) : ( 2nd )

The fact that the two 2nd pieces are also ternary has no effect on the process of the first.

The ternary operator, in the tradition of C, isn't really var ? var : var var ? var : var . It is in fact:

statement ? statement : statement

Which means, in place of a variable or value you can put code in there to evaluate and the return value of that code is taken as the value. So,

(i%3)?(i%5)?i:'Buzz':(i%5)?'Fizz':'FizzBuzz'

breaks down as:

(i%3) ?
         (i%5) ?
                  i
               :
                  'Buzz'
      :
         (i%5) ?
                  'Fizz'
               :
                  'FizzBuzz'

(basically what you wrote in your question, so your interpretation is correct)

It helps putting the : in separate lines so you can see the pattern. I've also aligned the ? with the : to see which is grouped with which.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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