const a = 'hi';
const b = 'newTextHI'
const str = `${a.toUpperCase()}${true && `\n${b.toUpperCase()}`}`;
console.log(str);
const c = 'hi';
const d = 'newTextHI'
const str2 = `${c.toUpperCase()}${false && `\n${d.toUpperCase()}`}`;
console.log(str2);
true
将被自动忽略,但 false
将被评估为字符串?
我明白三元运算符可以得到我想要的,但是我不明白为什么在上面的例子中 bool 值被区别对待
最佳答案
在expression1 && expression2
中,
如果 expression1
是 truthy
,它将返回 expression2
否则它将返回 expression1
。 ( Documentation )
如果链接,则重复应用相同的逻辑。它将检查直到 falsy
值被发现。如果未找到,则返回最后一个表达式。 ( Short-circuit evaluation )
// no falsy expressions here
// last expression returned: `string`
console.log(true && `string`)
// short-circuit at false, because what's the point of going further?
console.log(false && `string`)
// true, 100, "string" are all truthy
// 0 is a falsy value. So, this evaluates until 0 and returns it
console.log(true && 100 && `string` && 0 && "doesn't matter")
在您的情况下,您可以改用三元运算符:
const a = 'hi';
const b = 'newTextHI'
const decider = false;
const str = `${a.toUpperCase()}${decider ? `\n${b.toUpperCase()}` : ``}`;
console.log(str);
关于javascript - 字符串模板中的不同 bool 处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56033116/