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
364 views
in Technique[技术] by (71.8m points)

javascript - ==或===,我应该使用哪一个比较javascript中的两个对象? [重复](== or ===, which one should I use to compare two objects in javascript? [duplicate])

I do not mean deep comparison.

(我并不是说要进行深度比较。)

I just want to know if two variables refer to the same instance.

(我只想知道两个变量是否引用同一实例。)

Should I use a==b or a===b ?

(我应该使用a==b还是a===b ?)

Can two variables point to the same memory but with different types?

(两个变量可以指向相同的存储器但类型不同吗?)

Because javascript has no such concept as class in C++, I do not know what an object's type is.

(因为javascript没有C ++中类的概念,所以我不知道对象的类型是什么。)

Do all objects have the same type: "object" so === decides their types are equal?

(是否所有对象都具有相同的类型:“对象”,所以===确定它们的类型相等?)

If so, === would be the same as ==.

(如果是这样,===将与==相同。)

  ask by William translate from so

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

1 Reply

0 votes
by (71.8m points)

From A Drip of Javascript: Object Equality in Javascript :

(摘自Java滴:JavaScript中的对象平等 :)

... Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference .

(...诸如字符串和数字之类的基元通过它们的值进行比较,而诸如数组,日期和普通对象之类的对象则通过其引用进行比较 。)

That comparison by reference basically checks to see if the objects given refer to the same location in memory.

(通过引用进行的比较基本上检查了给定的对象是否引用了内存中的相同位置。)

Here is an example of how that works.

(这是一个如何工作的例子。)

 var jangoFett = { occupation: "Bounty Hunter", genetics: "superb" }; var bobaFett = { occupation: "Bounty Hunter", genetics: "superb" }; var callMeJango = jangoFett; // Outputs: false console.log(bobaFett === jangoFett); // Outputs: true console.log(callMeJango === jangoFett); 


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

...