简体   繁体   English

JavaScript true +/- true是否为false?

[英]Javascript true +/- true is false?

I am trying to get an expression to test if one field is null and treat is as false 我正在尝试获取一个表达式来测试一个字段是否为空并且将其视为false

a=true
b=true
-------------
true

 a=null
 b=true
 -------------
 true

but when I execute: 但是当我执行时:

var a=true;
var b=true;
alert((a+b) == true);   => false

It returns false, i don't get it. 返回false,我不明白。

var a=null;
var b=true;
alert((a+b) == true);   => true

The general solution for this in javascript is to use !! 使用javascript的一般解决方案是使用!! to parse to a boolean. 解析为布尔值。 !! negates the truthiness twice, resulting in a boolean which has the same truthiness of the original. 对真实性进行两次否定,得到布尔值,其布尔值与原始值相同。

You should then use && as a logical and operation. 然后,应将&&用作逻辑and运算。

var a=null;
var b=true;
console.log(!!a && !!b);   // false

Edit: An addendum on the strange + behaviour 编辑:关于奇怪的+行为的附录

The strangeness you're seeing when using + instead of && is because, in JavaScript, + coerces booleans to integers, with true becoming 1 and false becoming 0 . 您在使用+而不是&&时看到的奇怪之处是,在JavaScript中, +布尔值强制转换为整数,其中true变为1false变为0

Hence 因此

true + true \\ 2
true + false \\ 1

And then when doing 然后当做

true + true == true

the left-hand-side of the equality comparison resolves to 2 , JavaScript then coerces the right-hand-side to 1 and thus the equality check fails. 等式比较的左侧解析为2 ,JavaScript然后将其右侧强制为1 ,因此相等性检查失败。

When doing 做的时候

null + true == true

the left-hand-side becomes the integer 1 , and then so does the right. 左边变成整数1 ,右边变成整数1

I'd recommend reading the MDN guide on Equality comparisons and sameness for more on JavaScript's value coercion and abstract equality checks. 我建议阅读MDN关于平等比较和相同性的指南,以获取有关JavaScript的价值强制和抽象平等检查的更多信息。

 var a = true; var b = true; console.log((a & b) === 1); var c = null; console.log((a & c) === 1); 

true == 1 This is important. true == 1这很重要。 When you convert true to a number, it will be 1 当您将true转换为数字时,它将为1

then true + true == true becomes 2 == 1 which is false 然后true + true == true变成2 == 1这是false

similarly null + true == true becomes 1 == 1 which is true because null resolves to 0 同样, null + true == true变为1 == 1这是正确的,因为null解析为0

I think you are going about testing for null the wrong way. 我认为您打算以错误的方式测试null

try 尝试

alert((a & b) === 1); 

For null and true to test to true you could probably do: 为了将null和true测试为true,您可以执行以下操作:

!null === true

This might solve it for you. 这可能会为您解决。

It is simple. 很简单。 When you are trying to make + operation true is like 1 and false is like 0. Then if you make true+true you get 2 and two is not 1, so it is not true . 当您尝试使+运算为true ,就像1,而false则为0。然后,如果您使true+true ,则得到2而2不是1,所以它不是true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM