Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, so first you need to understand how javascript treats values in your program. All of your variables that you create are going to merely be references to a location in memory where that object is stored. Therefore, when you do this:

alert( [1,2,3] == [1,2,3] );

...it does three things:

  1. Place an array ([1,2,3]) onto the heap
  2. Place another array ([1,2,3]) onto the heap (notice it will have a different memory location)
  3. Compare the two references. They point to different objects in different locations in memory, thus it is considered not equal.

You can check for some sane behavior by running this code:

var a = [1,2,3];
var b = a;
alert (a == b)   // Result is true. Both point to the same object.

Now for your question about the string

When you use the == operator tries to convert the two operands to the same type (evil behavior...I know...)

When it does this, it decides to convert both to a string before it does the compare (thus the result is really "1,2,3" === "1,2,3", which evaluates to true.

I can't give you a complete picture, as there are few people who understand every nuance of the madness that is JavaScript, but hopefully this clears some of the fog.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...