简体   繁体   中英

ternary operation in js

Maybe I do not understand ternary operation but

if I am right it's

    test ? true : false

So this should give

function toto(x, y)
{ 
    return (x > 0 ? x < 7 ? true : false : false &&
                y > 0 ? y < 6 ? true : false : false)
}

true only if 0

but if I do

toto(4,6)

it returns true, why? What am I missing ?

you need eslint to format your code ,this is the formatted code,see:

function toto(x, y) {
  return x > 0
    ? x < 7
      ? true
      : false
    : false && y > 0
      ? y < 6
        ? true
        : false
      : false
}

image:

在此处输入图片说明 I think ,it is easier to understand

just do like this :

function toto(x, y)
{ 
    return (x > 0 ? x < 7 ? true : false : false ) &&
                ( y > 0 ? y < 6 ? true : false : false)
}

with the bracket before and after the exp1 and exp2 and yes it's a bit unreadable ^^

edit : I also would do

return (x > 0 && x < 7) && (y > 0 && y < 6)

Aren't you trying to achieve this? chceking whether the x is from 0..7 and y is 0..6?

function toto(x, y)
{ 
return (x > 0 && x < 7) && (y > 0 && y < 6 );
}

Operator precedence affecting it here

function toto(x, y)
{ 
return ((x > 0 ? x < 7 ? true : false : false) && (y > 0 ? y < 6 ? true : false : false)) 
}

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