Can anyone help me to understand the difference in obj1
and obj2
created in two ways in JavaScript? They look the same in the console.
var obj1 = { 'name': 'blue', 'shade': 'dark'};
var obj2 = JSON.parse('{"name":"blue","shade":"dark"}');
because
(obj1 === obj2) is false as
(obj1 == obj2) is false
while in javascript console show as
Object {name: "blue", shade: "dark"}
Object {name: "blue", shade: "dark"}
尽管对象的内容相同,但是您具有对两个单独对象的引用,这就是为什么==和===都失败(它们检查引用是否为内容)。
As ABucin said, javascript checks for references, if you still want to check if two jsons are equal you could try using
JSON.stringify(obj1) === JSON.stringify(obj2)
or check for every key (a bit more complicated but more efficient in the case that the keys are in different orders).
Try reading this:
you are creating an object with obj1 and in obj2 you parsing a JSON object into an object. Since both objects are different (different reference) they are treated as different
You can learn more on this over here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.