如何解读这段JavaScript中的条件分支代码?
解读这段嵌套三元表达式逻辑
先把原代码贴出来:
this.orientation = this.props.orientation ? this.props.orientation == 'horizontal' ? 'row' : 'column' : 'column';
这段是嵌套的三元运算符,拆成普通if-else结构就一目了然了:
if (this.props.orientation) { // 父组件传了orientation属性(值为真) if (this.props.orientation === 'horizontal') { this.orientation = 'row'; } else { // 只要传的不是'horizontal',不管是'row'还是其他值,都赋值为'column' this.orientation = 'column'; } } else { // 父组件没传orientation属性(值为假),直接赋值为'column' this.orientation = 'column'; }
简单总结所有情况:
- 父组件传
orientation="horizontal"→this.orientation是'row' - 父组件传
orientation为其他有效值(比如'row'、'vertical'等)→this.orientation是'column' - 父组件没传
orientation属性 →this.orientation是'column'
内容的提问来源于stack exchange,提问作者Marcus
相关产品推荐
相关产品推荐

