为什么[] === [](和其他人)在javascript中返回false? [英] Why does [] === [] (and others) return false in javascript?

查看:121
本文介绍了为什么[] === [](和其他人)在javascript中返回false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下比较在javascript中返回 false

The following comparisons all return false in javascript:

[]===[]
[]==[]
{}==={}
{}=={} 
[0]===[0]
[0]==[0]

> true :

However the following return true:

[0]=='0'
[0]==0
[]==false //(and all other == that were exampled above)

这是什么原因?特别是 [0]!= [0] [0] == 0之间的区别

What is the reason for this? Especially the difference between [0]!=[0] and [0]==0

小提琴: http://jsfiddle.net/vnBVj/ p>

Fiddle: http://jsfiddle.net/vnBVj/

推荐答案

这是由于混乱的规则,javascript是如何强制类型。您可以在§11.9.3的EcmaScript 5规范中阅读。

This is due to the confusing rules, how javascript does type coercion. You can read about this in §11.9.3 of the EcmaScript 5 spec.

两个对象(数组也是)从不相等,因此您在第一个块中的所有比较都会产生false(§11.9.3.1.c.vi)

Two Objects (which Arrays are too) are never equal, thus all your comparisons in the first block yield false (§11.9.3.1.c.vi)

第二个方块比较困难:

首先要知道的是, ==

First thing to know is, that == uses type coercion to compare the operands.

当比较包含布尔值时,这一个首先被强制转换为一个数字。

When a comparison has a Boolean involved, this one is first coerced to a number.

[]==false
[]==0

之后,通过调用 Object.prototype.toString

"" == 0

变为 0

0 == 0

通过应用相同的规则,您可以看到为什么您的其他示例也产生真实。

yielding true. By applying the same rules, you can see why your other examples also yield true.

请注意 === 从不引起类型强制,但首先检查正确的类型,如果它们不相等则产生false。只有类型相等,才比较实际值。所以这种比较方法比 == 更可靠。

Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal! Only if the types are equal, it compares the actual values. So this method of comparison is far more reliable than ==.

这篇关于为什么[] === [](和其他人)在javascript中返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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