javascript - JS: weird object comparison behavior
问题描述
Given this code:
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
Why does double-equals comparison return true
when using the name
variable, but not an object literal?
First, I thought that maybe it's because the objects have the same memory address, but as one can see it's not true.
Moreover, if we turn things upside-down and define the variable inside the function, the comparison returns false
! (It is not shown in the code but you can check it out)
I'm seriously confused and will appreciate the explanation.
EDIT: Here is where I have tested the code. Nodejs and browser console in Chrome give me the regular results, how it should be. So maybe it is something about the interpreter.
解决方案
您假设 Javascript 会==
按照您的想法执行比较,但事实并非如此。但由于这是一个自定义对象,您不能指望 Javascript 为您提供开箱即用的自定义实现。你应该自己实现它。
唯一可行的情况是当您使用===
运算符检查对象是否相同但通过它们的内存地址时,从而跳过任何custom-object-data-based
比较。
推荐阅读
- python - 如何在循环已经运行时继续执行代码
- javascript - 选择时从语义 ui 反应下拉列表中选择的值不出现
- algorithm - 这个算法是否涵盖了所有情况下找到最小硬币变化的总和?
- oop - 在 RBAC 中向用户授予特殊权限
- buildfire - Buildfire:找不到我创建的插件,即使我上传了它
- dataframe - Julia - 错误:无法从模块 Main 分配变量 ImageAxes.data
- python - 使 CPLEX 使用贪心解决方案
- cakephp - Cake php无法设置主页
- python - Django Url 路由器上的问题
- angular - 获取 ng-content 中的所有项目