首页 > 解决方案 > 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.

标签: javascriptobjectvariablescomparison

解决方案


您假设 Javascript 会==按照您的想法执行比较,但事实并非如此。但由于这是一个自定义对象,您不能指望 Javascript 为您提供开箱即用的自定义实现。你应该自己实现它。

唯一可行的情况是当您使用===运算符检查对象是否相同但通过它们的内存地址时,从而跳过任何custom-object-data-based比较。


推荐阅读