gpt4 book ai didi

javascript - 字符串模板中的不同 bool 处理?

转载 作者:行者123 更新时间:2023-11-30 11:04:57 25 4
gpt4 key购买 nike

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中,

如果 expression1truthy ,它将返回 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com