我试图在链接时在我的三元运算符中使用逻辑运算符&&,但它不起作用…例如:
(x === 5 && y === 5) ? (do something)
: (x === 5 && y === 4) ? (do something else)
: (x === 5 && y === 3) ? (do a third thing)
: null
这个是可能的吗?有没有其他方法可以做到这一点?
发布于 2019-12-22 22:07:04
x === 5 ?
y === 5 ? console.log('x=5, y=5') :
y === 4 ? console.log('x=5, y=4') :
y === 3 ? console.log('x=5, y=3') : null
: null证明:
const resp = (x,y) => x === 5 ?
y === 5 ? 'x==5, y==5' :
y === 4 ? 'x==5, y==4' :
y === 3 ? 'x==5, y==3' : 'x==5, y==?'
: 'x==?, y==?'
console.log ( '1 ,2 ', resp(1,2) ) // 1 ,2 x==?, y==?
console.log ( '5 ,2 ', resp(5,2) ) // 5 ,2 x==5, y==?
console.log ( '5 ,4 ', resp(5,4) ) // 5 ,4 x==5, y==4
发布于 2019-12-22 22:33:10
是的,你可以按你的方式去做:
const Question = (x,y) => (x === 5 && y === 5) ? 'x==5, y==5'
: (x === 5 && y === 4) ? 'x==5, y==4'
: (x === 5 && y === 3) ? 'x==5, y==3'
: 'x==?, y==?'
console.log ( '1 ,2 ', Question(1,2) ) // 1 ,2 x==?, y==?
console.log ( '5 ,2 ', Question(5,2) ) // 5 ,2 x==?, y==?
console.log ( '5 ,4 ', Question(5,4) ) // 5 ,4 x==5, y==4
发布于 2019-12-22 22:01:55
使用圆括号指定成功和失败的嵌套条件。
(x === 5 && y === 5) ? (do something) : ((x === 5 && y === 4) ? (do something
else) : ((x === 5 && y === 3) ? (do a third thing) : null));证明:
const test = (x,y) => (x === 5 && y === 5)
? 'x==5, y==5'
: ( (x === 5 && y === 4)
? 'x==5, y==4'
: ( (x === 5 && y === 3)
? 'x==5, y==5'
: 'x==?, y==?'
) );
console.log ( '1 ,2 ', test(1,2) ) // 1 ,2 x==?, y==?
console.log ( '5 ,2 ', test(5,2) ) // 5 ,2 x==?, y==?
console.log ( '5 ,4 ', test(5,4) ) // 5 ,4 x==5, y==4
https://stackoverflow.com/questions/59444825
复制相似问题