在javascript中,三等号对于数组返回false。为什么? [英] Triple equal signs return false for arrays in javascript. why?

查看:178
本文介绍了在javascript中,三等号对于数组返回false。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 === 通常被称为身份运营商。被比较的值必须具有相同的类型和值才能被视为相等。那么为什么下面的行返回false?

I know that === is typically referred to as the identity operator. Values being compared must be of the same type and value to be considered equal. Then why below line returns false?

数组(asdf)===数组(asdf)

推荐答案

它们不相等,因为在每个语句中都创建了一个新数组,每个数组都是一个全新的数组对象只是相同的内容。如果您创建两个新对象:

They are not equal because a new array is being created in each of these statements, each being a brand new array object with just identical contents. If you create two new objects:

var a = {};
var b = {};

a === b // false

创建新对象时,数组,函数等,一个全新的对象被放入内存。使用与另一个对象相同的内部构造创建一个新对象不会神奇地导致该对象指向已存在的对象。对象可能看起来相同,但它们不指向同一个实例。现在,如果你的陈述是这样的话:

When you create new objects, arrays, functions, etc., a brand new object is placed into memory. Creating a new object with the same internals as another object will not magically cause that object to point to one that already exists. The objects may look the same, but they do not point to the same instance. Now if your statement had been like so:

var arr = ['asdf'];

arr === arr; // true

这显然是真的。 === 是严格相等,而不是身份运算符。当对象通过严格相等运算符运行时,将检查它们是否指向相同的引用。正如我之前解释的那样,每次使用 new Array [] 时,都会创建一个全新的对象,是一个新的和不同的参考。所以两个数组或任何对象都不可能出现 === 为真,除非他们指向确切的相同的数组。仅仅因为使用相同内容创建两个对象并不意味着它们指向同一个对象,只是指向两个相同但不同的对象。

This is obviously be true. === is strict equality, not an identity operator. When objects are ran through a strict equality operator, they are checked to see if they point to the same reference. As I explained earlier, each time you use new Array or [] that a brand new object will be created, each being a new and different reference. So there is no way that two arrays, or any object, can come out === being true unless they point to the exact same array. Just because two objects are being created with identical contents does not mean that they point to the same object, just two identical, but different objects.

考虑构造函数:

var Car = function (color) {
    this.color = color;
};

var ford = new Car('green');
var chevy = new Car('green');
var toyota = ford;

ford === chevy // false

仅仅因为你在使用相同的构造函数并不意味着每次调用它时都会返回相同的对象。相反,每次都会返回一个新对象。仅仅因为两辆车都是绿色并不意味着它是同一辆车。

Just because you are using the same constructor does not mean that every time you call it the same object gets returned. Rather, a new object will be returned every time. Just because both cars are green doesn't mean it's the same car.

ford === toyota // true

现在这是真的,因为两个变量都指向完全相同的 Car 参考。

This is now true because both variables point to the exact same Car reference.

这篇关于在javascript中,三等号对于数组返回false。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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