逻辑运算符和javascript中的两个字符串 [英] Logical operator && and two strings in javascript

查看:64
本文介绍了逻辑运算符和javascript中的两个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I use the logical operator && between two strings, why does it give me the second string as output:

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

我认识到,除了0falsenullundefined""NaN之外,其他所有内容都在类似一个逻辑表达式中被评估为布尔值true以上.但是,为什么输出是第二个字符串而不是第一个字符串?又因为输出被评估为布尔表达式,为什么输出不只是"true"呢?

I realize that the with the exception of 0, false, null, undefined, "" and NaN, everything else is evaluated as a boolean true in a logical expression like the one above. But why is the output the second string and not the first? And why is the ouput not just "true" since it is being evaluated as a boolean expression?

推荐答案

在表达式中

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

由于您使用的是&&,因此JavaScript向您保证,它将验证表达式的两边都是true.在这种情况下,"Dog"是最后评估的东西.

Because you're using &&, JavaScript is promising you that it will verify that both sides of the expression are true. In this case, "Dog" is the just the last evaluated thing.

更明确地说,您可以执行类似的操作

To be more explicit, you could do something like

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

有点罗word,但这归结为

It's a little bit more wordy, but this boils down to

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

如果要为布尔值提供简单的快捷方式,请使用Boolean构造函数-

If you want a simple shortcut for the boolean, use the Boolean constructor -

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

如果仅使用简单的REPL或JavaScript控制台,就可以非常轻松地看到此输出.

If you just use a simple REPL or JavaScript console, you'd be able to see this output very easily.

根据以下评论之一

使用||,JavaScript向您保证,至少一个侧面是true.由于"Cat"为真,因此它将在此处停止并返回"Cat".这称为短路评估

Using ||, JavaScript is promising you that at least one of the sides is true. Since "Cat" is true, it stops there and returns "Cat". This is known as Short-circuit evaluation

这篇关于逻辑运算符和javascript中的两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆