2017-09-20 41 views
1

我被从名单上here检查所有falsey值的平等测试JavaScript中的所有falsy值不等于假不打印hi为什么当平等

if(null == false) console.log('hi'); 
if(undefined == false) console.log('hi'); 
if(NaN == false) console.log('hi'); 

所有其他falsey值最终打印文本hi,如下图所示:

if('' == false) console.log('hi'); 
if(0x0 == false) console.log('hi'); 
if(false == false) console.log('hi'); 
if(0.0 == false) console.log('hi'); 
if(0 == false) console.log('hi'); 

任何人都可以帮我理解这种行为背后的原因吗?

更新为未来的读者

如果你想环绕falsy价值观和平等经营的怪事你的头在JavaScript

三个有趣的记载:

  1. why null==undefined is true in javascript
  2. Why does (true > null) always return true in JavaScript?
  3. What exactly is Type Coercion in Javascript?
+5

了''==操作符的语义是不与用于布尔值的任意值的评估规则相同。 – Pointy

+0

在这里阅读关于强制类型,你会更好地理解它:https://stackoverflow.com/questions/19915688/what-exactly-is-type-coercion-in-javascript – pegla

+3

具体来说,'=='(或“松散等于“)运算符[比较两个值的均等性_after_将这两个值转换为常见类型](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using) – Hamms

回答

2

==运算符有其自己的语义。你正在比较没有被定义为相同的行为。

如果你想看到正常的“truthy/falsy”的评价工作,你应该使用的value == falsevalue == true!value!!value代替:

if (!null) console.log("hi"); 
if (!NaN) console.log("hi"); 
相关问题