Why is [] !== [] in JavaScript? [duplicate]

谁都会走 提交于 2019-11-26 21:21:02

问题


This question already has an answer here:

  • Why isn't [1,2,3] equal to itself in Javascript? 6 answers

Why is [] !== [] in JavaScript?

I read through https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness but I could not find anything that explains this.

Edit: I don't think this question or this question is an exact duplicate of mine. It asks about the == operator which just behaves crazy. The answer is an answer to my question but it's not the same question.


回答1:


That does a reference check on the two array literals to see if they are the same instance. The fact that you have two literals means that you are constructing two separate arrays, therefore the reference check returns false. This would return true:

var a = []
var b = a

//b === a

This is because we have two references to the same array.




回答2:


[] creates a new (and empty) array each time you write it. You are comparing two arrays, regardless of their content, their pointer (or reference) are being compared.

var array = [];
var anotherArray = array; // these two will point to the same array, so they are equal


array === anotherArray; // true
array === []; // false


array.push('something');
anotherArray.length; // 1



回答3:


Because [] is an object, and a comparison of objects only returns true when both sides of the comparison point to the exact same object. You have created two separate objects, so they aren't equal.

var x = []
var y = x
var z = []

x == x // true
x == y // true
x == z // false


来源:https://stackoverflow.com/questions/40313263/why-is-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!