Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. 不能使用 "==" 或 "===",返回false
  2.  
  3. >原因是基本类型string,number通过值来比较,而引用类型(Date,Array)及普通对象通过指针指向的内存中的地址来比较
  4.  
  5. 自定义判断函数:
  6. ```
  7. function isObjectValueEqual(a, b) {
  8. // Of course, we can do it use for in
  9. // Create arrays of property names
  10. var aProps = Object.getOwnPropertyNames(a);
  11. var bProps = Object.getOwnPropertyNames(b);
  12.  
  13. // If number of properties is different,
  14. // objects are not equivalent
  15. if (aProps.length != bProps.length) {
  16. return false;
  17. }
  18.  
  19. for (var i = 0; i < aProps.length; i++) {
  20. var propName = aProps[i];
  21.  
  22. // If values of same property are not equal,
  23. // objects are not equivalent
  24. if (a[propName] !== b[propName]) {
  25. return false;
  26. }
  27. }
  28.  
  29. // If we made it this far, objects
  30. // are considered equivalent
  31. return true;
  32. }
  33. ```
  34.  
  35. 在很多情况下,这个自定义函数是不能处理的
  36. - 属性值本身就是一个对象
  37. - 属性值中存在NaN
  38. - 一个对象的属性值中存在undefined,而另一个对象不存在
  39.  
  40. 可以借助一些JS库: Underscore或Lo-Dash的_.isEqual()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement