也许这会澄清一些事情:
let a = {}; // Object Literal
let b = {}; // Object Literal
let c = a;
// both a and b above are separate objects
console.log(b == a) // false
console.log(c == a) // true
console.log({} == {}) // false, as both are different Objects
// if you want to test if two things are the same type you could do
console.log(({}).toString() == ({}).toString()) // true
console.log(a.toString() == b.toString()) // true
// the reason why those work is, because now we are comparing strings... not the objects
console.log(({}).toString()) // "[object Object]"
// to simply check that the Object is "true", you could.
console.log(!!{});
// Specifying your own false, if empty comparisons "as values"...
console.log(!!Object.keys({}).length) // false
// or, even
console.log( !("{}" == JSON.stringify({}) ) ) // false
如果感兴趣的对象有可能是函数或包含任何非 json 安全值,我会警告不要使用 JSON.stringify,因为在比较函数或误报的情况下会出现错误
JavaScript 平等
=== 是严格相等比较(“identity”)
== 是抽象平等比较(“松散平等”)
“===”很简单,被比较的对象是同一个对象“实例”
“==”有点复杂,因为强制开始发挥作用,所以它更像是“它们可以一样吗”
查看这篇文章,了解正在发生的事情的机制......
松散等式与严格等式
松散等于是 == 运算符,严格等于是 === 运算符。这两个运算符都用于比较“平等”的两个值,但“松散”与“严格”表明两者之间的行为存在非常重要的差异,特别是它们如何决定“平等”。
关于这两个运算符的一个非常常见的误解是:“== 检查值是否相等,=== 检查值和类型是否相等。” 虽然这听起来不错且合理,但它是不准确的。无数备受推崇的 JavaScript 书籍和博客都明确表示过这一点,但不幸的是,它们都错了。
正确的描述是:“== 允许在相等比较中进行强制转换,而 === 不允许进行强制转换。