我正在尝试基于标志值构建字符串

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'}`;


如果flag为true,则显示完美答案

2014 Chevy Malibu Electric: false |hatchback


尝试的代码:
    如果标志为假,
    返回${super.getDetails()} Electric: ${this.isElectric} ${flag && '|hatchback'};

预期:

2014 Chevy Malibu Electric: false


实际:

2014 Chevy Malibu Electric: false false

最佳答案

使用三元运算符而不是逻辑运算符,因此可以在返回假字符串时返回一个空字符串。

return `${super.getDetails()} Electric: ${this.isElectric} ${false ? '|hatchback' : ''}`;

return `${super.getDetails()} Electric: ${this.isElectric} ${true ? '|hatchback' : ''}`;

08-08 04:10