关于javascript:三元运算符

Expression “Something” ? “Something” : “Something else” shorter?

本问题已经有最佳答案,请猛点这里访问。

快速提问。我可以用更短的方式写吗?

{this.state.members[activeMemberId].id ? this.state.members[activeMemberId].id : null}

例如

{this.state.members[activeMemberId].id ? <-the same : null}


你只需做:

1
this.state.members[activeMemberId].id || null

您可以使用逻辑或

1
{ this.state.members[activeMemberId].id || null }

这是怎么工作的?

1
2
3
   x  ||  y
   |
   |________________ If `x` is true return `x` else return `y`

经验法则:逻辑或返回第一个真值如果还有其他值,则返回最后一个值


注意不要在访问undefined的id属性时出现未定义的引用异常。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function getMemberId(activeMemberId) {
    this.state = { members: {
      id1: { id: 1 }
    } };
    const { members: { [activeMemberId]: { id = null } = {} } = {} } = this.state;
    return id;
 }
 
 console.log(getMemberId('id1'));
 console.log(getMemberId('id2'));
 
 // Or you could chain the && operator and || operator
 function getMemberIdAlt(activeMemberId) {
    this.state = { members: {
      id1: { id: 1 }
    } };
   
    return (
      this.state
      && this.state.members
      && this.state.members[activeMemberId]
      && this.state.members[activeMemberId].id
    ) || null;
 }
 
 console.log(getMemberIdAlt('id1'));
 console.log(getMemberIdAlt('id2'));


您可以使用||

1
this.state.members[activeMemberId].id || null