Null是类型对象,所以它是真的吗?在幕后发生了什么? [英] Null is type object, so it's truthy? What's going on behind the scenes?

查看:279
本文介绍了Null是类型对象,所以它是真的吗?在幕后发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的书优雅JavaScript中读到, null == true 计算结果为false。使用解释器,我已经确认这是 TRUE 。然而,在本章的后面 - 事实上,在同一页 - ,它说,当null作为if,while或for语句的条件,它将被转换为布尔值并返回false。 / p>

任何有深入洞察力的人都能告诉我为什么会这样?我知道在哪里可以找到浏览器源代码,但我不知道如何定位的负责这种奇特和unintuive行为的编程。因为我知道很少的C ++,我也会感谢任何提示,独立地找到这样的信息。



谢谢。

解决方案

要做的一个重要区别是 Type of null Null



(忽略 typeof 会返回object null ,因为设计不良和向后兼容性)


11.9.3抽象平等比较算法#Ⓣ比较
x == y,其中x和y是值,生成true或false。这样的
比较执行如下:



[... stripped]


  1. 返回false。


ES5规格



表示与 null 和 Boolean 应该返回false,因为 Type > Null Boolean 不相同,11.9.3中的其他步骤都不适用,因此默认操作 return false 发生

只有 Type c> x 和 y y 是 null == 操作仍返回 true


如果x为null且y未定义,则返回true。



如果x未定义,y为null,则返回true。


这意味着 undefined == null 返回 true



strong>特别注意:



有一个 ES6:和谐提案以修复 typeof null


I'm reading in my book, "Elegant JavaScript", that null == true evaluates as false. Using an interpreter, I have confirmed this to be TRUE. However, later in the chapter--in fact, on the same page--, it says that when null is given as the condition of an if, while, or for statement, it will be converted to a Boolean and return false.

Can anybody with a deeper insight tell me why this is? I know where to find browser source code, but I'm not sure how to target the programming that is responsible for this peculiar and unintuive behavior. Because I know very little C++, I would also appreciate any tips on finding info like this, independently.

Thank you.

解决方案

An important distinction to make is that the Type of null is Null.

(ignore typeof it returns "object" for null because of bad design and backwards compatibility)

11.9.3 The Abstract Equality Comparison Algorithm # Ⓣ The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

[... stripped]

  1. Return false.

The ES5 specification

Says that the comparison with null and a Boolean should return false because the Type of Null and Boolean are not the same, and none of the other steps in 11.9.3 apply so the default action of return false happens

The only case where the Type of x and y are different and either x or y is null but the == operation still returns true are

If x is null and y is undefined, return true.

If x is undefined and y is null, return true.

That means undefined == null returns true

Of special note:

There is an ES6:harmony proposal to fix typeof null

这篇关于Null是类型对象,所以它是真的吗?在幕后发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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