[]与[]不同 [英] [] is not identical to []

查看:80
本文介绍了[]与[]不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求用Javascript写一个函数sortByFoo,它将对该测试做出正确的反应:

I was asked to write a function sortByFoo in Javascript that would react correctly to this test :

// Does not crash on an empty array
console.log(sortByFoo([]) === []);

但是我尝试了一些事情:

But I've tried something :

[] === [];
>> false

所以我可以肯定,无论sortByFoo函数如何,这样的测试总是会失败,不是吗? 但是,我想解释为什么会这样.为什么[]与[]不相同/相等?

Just so I can be sure, such a test would always fail, no matter the sortByFoo function, wouldn't it ? But I'd like to have an explanation on why this happens. Why [] isn't identical/equal to [] ?

请原谅我大概的英语,这不是我的母语:p

Please forgive my approximate english, it is not my native language :p

推荐答案

如果您查看javascript/ecmascript规范,尤其是

If you look at the specification for javascript/ecmascript, particularly section 11.9.6, you will see how comparisons with === are performed.

严格相等比较算法

比较x === y(其中x和y是值)产生true或false.这样的比较如下:

The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. 如果Type(x)与Type(y)不同,则返回false.
  2. 如果Type(x)未定义,则返回true.
  3. 如果Type(x)为Null,则返回true.
  4. 如果Type(x)为Number,则
    • 如果x为NaN,则返回false.
    • 如果y为NaN,则返回false.
    • 如果x与y相同,则返回true.
    • 如果x为+ 0,y为−0,则返回true.
    • 如果x为−0且y为+0,则返回true.
    • 返回false.
  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Undefined, return true.
  3. If Type(x) is Null, return true.
  4. If Type(x) is Number, then
    • If x is NaN, return false.
    • If y is NaN, return false.
    • If x is the same Number value as y, return true.
    • If x is +0 and y is −0, return true.
    • If x is −0 and y is +0, return true.
    • Return false.

由于数组一直进行到第七步,它们将必须是同一对象,而不仅仅是两个相同的对象.常规相等运算符(==)也是如此.

Since your arrays go all the way down to the seventh step they will have to be the same object, not just two identical objects. The same goes for the regular equality operator (==).

这篇关于[]与[]不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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