如何阅读条件运算符中的 IN 关键字?

How do you read the IN keyword inside a conditional operator?

偶然发现了这段代码: var text = 'text' in this.props ? this.props.text : ''; 但即使我了解上下文,我也很难阅读这一行。它被描述为防御性代码,因为在 React 中它可以被替换为 getDefaultProps() 方法

这是看有没有道具叫text。如果是这样,三元表示 var text = this.props.text;。如果this.props中没有text,则三元表示var text = '';。这是防御性代码,因为它使 text 成为一个字符串而不是 undefined 如果它不包含在道具中。

in 运算符检查 属性 是否是对象的成员。

('text' in this.props) ≈≈ (Object.keys(this.props).includes('text'))

所以代码片段正在做的是检查 text 是否在 this.props 中定义,如果是,则返回它,否则返回一个空的 String.