Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 不能使用 "==" 或 "===",返回false
- >原因是基本类型string,number通过值来比较,而引用类型(Date,Array)及普通对象通过指针指向的内存中的地址来比较
- 自定义判断函数:
- ```
- function isObjectValueEqual(a, b) {
- // Of course, we can do it use for in
- // Create arrays of property names
- var aProps = Object.getOwnPropertyNames(a);
- var bProps = Object.getOwnPropertyNames(b);
- // If number of properties is different,
- // objects are not equivalent
- if (aProps.length != bProps.length) {
- return false;
- }
- for (var i = 0; i < aProps.length; i++) {
- var propName = aProps[i];
- // If values of same property are not equal,
- // objects are not equivalent
- if (a[propName] !== b[propName]) {
- return false;
- }
- }
- // If we made it this far, objects
- // are considered equivalent
- return true;
- }
- ```
- 在很多情况下,这个自定义函数是不能处理的
- - 属性值本身就是一个对象
- - 属性值中存在NaN
- - 一个对象的属性值中存在undefined,而另一个对象不存在
- 可以借助一些JS库: Underscore或Lo-Dash的_.isEqual()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement