我正在尝试根据标志值构建一个字符串
return `${super.getDetails()} Electric: ${this.isElectric} ${flag && '|hatchback'}`;
如果标志为 false,则显示 - 2014 Chevy Malibu Electric: false false
我希望它显示2014 Chevy Malibu Electric: false
return `${super.getDetails()} Electric: ${this.isElectric} ${flag && '|hatchback'}`;
如果标志为 true,这将显示完美的答案
2014 Chevy Malibu Electric: false |hatchback
尝试过的代码:
当flag为假时,
返回${super.getDetails()}电动:${this.isElectric} ${flag && '|hatchback'}
;
预期:
2014 Chevy Malibu Electric: false
实际:
2014 Chevy Malibu Electric: false false
最佳答案
使用三元运算符而不是逻辑运算符,这样当结果为 false 时可以返回空字符串。
return `${super.getDetails()} Electric: ${this.isElectric} ${false ? '|hatchback' : ''}`;
return `${super.getDetails()} Electric: ${this.isElectric} ${true ? '|hatchback' : ''}`;
关于javascript - 仅当 flag 为 true 时才应显示该字符串,但如果为 false,则该 flag 会添加到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54260743/