首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有逻辑运算符的三元运算符

带有逻辑运算符的三元运算符
EN

Stack Overflow用户
提问于 2019-12-22 21:58:15
回答 3查看 397关注 0票数 0

我试图在链接时在我的三元运算符中使用逻辑运算符&&,但它不起作用…例如:

代码语言:javascript
复制
(x === 5 && y === 5) ? (do something) 
: (x === 5 && y === 4) ? (do something else) 
: (x === 5 && y === 3) ? (do a third thing) 
: null

这个是可能的吗?有没有其他方法可以做到这一点?

EN

回答 3

Stack Overflow用户

发布于 2019-12-22 22:07:04

代码语言:javascript
复制
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

证明:

代码语言:javascript
复制
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

票数 3
EN

Stack Overflow用户

发布于 2019-12-22 22:33:10

是的,你可以按你的方式去做:

代码语言:javascript
复制
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

票数 1
EN

Stack Overflow用户

发布于 2019-12-22 22:01:55

使用圆括号指定成功和失败的嵌套条件。

代码语言:javascript
复制
    (x === 5 && y === 5) ? (do something) : ((x === 5 && y === 4) ? (do something
      else) : ((x === 5 && y === 3) ? (do a third thing) : null));

证明:

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59444825

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档