-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[js] 第392天 如何判断两个对象相等? #2365
Labels
js
JavaScript
Comments
JSON.stringify(obj)==JSON.stringify(obj) |
提供另一种写法: function isSameObject(object1, object2) {
if (Object.prototype.toString.call(object1) === '[object Object]' &&
Object.prototype.toString.call(object2) === '[object Object]') {
if (Object.keys(object1).length !== Object.keys(object2).length) {
return false;
}
for (let key in object1) {
if (!object2[key] || object1[key] !== object2[key]) {
return false;
}
}
}
return true;
} 当然JSON.stringify(obj)==JSON.stringify(obj)执行速度是最快的 |
写了一个可以判断嵌套对象的 function equals(a, b) {
const tostring = Object.prototype.toString;
const objType = '[object Object]';
if (tostring.call(a) !== objType || tostring.call(a) !== objType) {
return false;
}
const lenA = Object.keys(a).length;
const lenB = Object.keys(b).length;
if (lenA !== lenB) {
return false;
}
for (const key in a) {
if (a.hasOwnProperty(key) && !b.hasOwnProperty(key)
|| !a.hasOwnProperty(key) && b.hasOwnProperty(key)
) {
return false;
}
if (tostring.call(a[key]) === objType) {
if (!equals(a[key], b[key])) {
return false;
}
} else {
if (a[key] !== b[key]) {
return false;
}
}
}
return true;
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
第392天 如何判断两个对象相等?
我也要出题
The text was updated successfully, but these errors were encountered: