gpt4 book ai didi

javascript - javascript中的逻辑运算符&&和两个字符串

转载 作者:行者123 更新时间:2023-12-03 00:19:32 27 4
gpt4 key购买 nike

当我在两个字符串之间使用逻辑运算符 && 时,为什么它会给我第二个字符串作为输出:

console.log("" && "Dog");    // ""
console.log("Cat" && "Dog"); // "Dog"

我意识到除了0falsenullundefined ""NaN,其他所有内容在类似于上面的逻辑表达式中都被计算为 bool 值 true。但为什么输出是第二个字符串而不是第一个?为什么输出不只是“true”,因为它被评估为 bool 表达式?

最佳答案

在表达式中

"Cat" && "Dog"
// => "Dog"

因为您使用的是 &&,JavaScript 向您保证它将验证表达式两边都为 true。在本例中,“Dog” 是最后一个评估的事物。

更明确地说,你可以这样做

var c = "Cat" != null && "Dog" != null

虽然有点啰嗦,但归结起来就是

var c = true && true
console.log(c)
// => true

如果您想要 bool 值的简单快捷方式,请使用 Boolean 构造函数 -

var c = Boolean("Cat" && "Dog")
console.log(c)
// => true

如果您只使用简单的 REPL 或 JavaScript 控制台,您将能够非常轻松地看到此输出。

<小时/>

根据下面的评论

使用||,JavaScript 向您保证至少有一个边是true。由于“Cat”为真,因此它停在那里并返回“Cat”。这称为 Short-circuit evaluation

关于javascript - javascript中的逻辑运算符&&和两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17200315/

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