[英]JS: weird object comparison behavior
给出以下代码:
const name = { name: 'amy' }; function greet(person) { if (person == { name: 'amy' }) { return 'hey amy'; } else { return 'hey there'; } } console.log( greet(name) // 'hey amy' ); console.log( greet({ name:'amy' }) // 'hey there' ); console.log(name == { name: 'amy' }); // true console.log(name === { name: 'amy' }); // false console.log(Object.is(name, { name: 'amy' })); // false
为什么在使用name
变量而不是对象文字时双精度比较返回true
?
首先,我认为可能是因为对象具有相同的内存地址,但是正如人们看到的那样,这是不正确的。
而且,如果我们颠倒过来并在函数内部定义变量,则比较返回false
! (代码中未显示,但您可以签出)
我很困惑,不胜感激。
编辑: 这是我测试过代码的地方。 Chrome中的Nodejs和浏览器控制台为我提供了常规结果,应该是这样。 所以也许是关于口译员的事。
您假定您在脑海中就想着Javascript将使用==
进行比较,但事实并非如此。 但是由于这是一个自定义对象,所以您不能指望Javascript会为您提供自定义实现。 您应该自己实现它。
唯一可行的情况是,使用===
运算符检查对象是否相同,但按其内存地址进行检查,从而跳过任何custom-object-data-based
比较。
这里的问题是为变量使用单词name
。
在浏览器中, window
对象具有name
属性,该属性必须始终为字符串。 如果您尝试为其分配非字符串的内容,它将被转换为一个。
然后,当您将一个对象与一个字符串进行比较时,该对象也将被转换并比较两个字符串。 这就是为什么您看到它有时返回true的原因。 例:
// This will end up being assigned to window.name, and will be converted to a string. var name = {name: "amy"} console.log(name) // [object Object] // Then, when you compare that to another object using ==, the object will also be converted to string. console.log(name == {name: "amy"}) // true, because the string [object Object] is equal to itself.
将变量的名称更改为其他名称,或者使用let
或const
,问题应消失:
// This will end up being assigned to window.other, but isn't converted to string var other = {name: "amy"} console.log(other) // {"name": "amy"} // Now, both are objects, and unless they are the exact same object, comparing two objects is always false. console.log(other == {name: "amy"}) // false, no two distinct objects are ever equal
// Using let will not assign this variable to window. let name = {name: "amy"} console.log(name) // {"name": "amy"} // Again, now we compare two distict objects, which always results in false. console.log(name == {name: "amy"}) // false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.