我正在写一个关于 javascript thruthiness 的小游戏,我发现了一些奇怪的东西。
eval('{}=={}') // error
{}=={} // false in the console but is an error in a source file
eval('[]==[]') // no error => false
eval('{}') // no error => undefined
eval('({})') // no error => Object
eval('[]') // no error => Array
Run Code Online (Sandbox Code Playgroud)
为什么 eval('{}=={}') 是一个错误,为什么 eval 包含 {} 的东西如此不一致?
小智 1
嗯,在 JavaScript 中,每个Object都是不同的。任何时候一个对象开始发挥作用,它就永远不会==/===另一个对象。即使它们是相同的
{}=={} // false
[]==[] // false
[1][0]==[1][0] // true
{id: 1}.id=={id: 1}.id // true
Run Code Online (Sandbox Code Playgroud)
一种方法是使用JSON.stringify来获取给定参数的字符串值
// Option 1
JSON.stringify({}) == JSON.stringify({}) // true
JSON.stringify([]) == JSON.stringify([]) // true
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用我创建的函数来比较两个对象/数组/字符串/等
// Option 2
Object.prototype.forEach = function forEach(callback) {
for (i in this) {
if (!this.hasOwnProperty(i)) continue;
callback(i, this[i])
}
}
Object.equals = function equals(obj1,obj2) {
var match = true;
if (typeof obj1 !== typeof obj2) {
return false;
} else if (typeof obj1 !== "object" && typeof obj2 !== "object") {
return obj1 === obj2;
} else if (JSON.stringify(obj1) == JSON.stringify(obj2)) {
return true;
}
obj1.forEach((value,key) => {
console.log(key, value)
if (obj2[key] !== value) {
match = false;
return;
}
})
return match;
}
Object.equals({},{}) // true
Object.equals("hello","goodbye") // false
Object.equals([],{}) // true because both of these different items are empty instances of objects.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |