Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.06 KB | None | 0 0
  1. # 有以下 3 个判断数组的方法,请分别介绍它们之间的区别和优劣
  2. > Object.prototype.toString.call() 、 instanceof 以及 Array.isArray()
  3.  
  4. MA:
  5. 1. `Object.prototype.toString.call()` 可以判断所有的基本类型
  6. 2. `instanceof ` 的内部机制是通过判断对象的原型链中是不是能找到类型的 `prototype`,只能对对象使用,不是能对基本类型使用。
  7. 3. `Array.isArray()` 是新增的方法,可以使用 `Object.prototype.toString.call()`来模拟。
  8.  
  9. ## OA:
  10.  
  11. 1. Object.prototype.toString.call()
  12. 每一个继承 Object 的对象都有 toString 方法,如果 toString 方法没有重写的话,会返回 [Object type],其中 type 为对象的类型。但当除了 Object 类型的对象外,其他类型直接使用 toString 方法时,会直接返回都是内容的字符串,所以我们需要使用call或者apply方法来改变toString方法的执行上下文。
  13. ```js
  14. const an = ['Hello','An'];
  15. an.toString(); // "Hello,An"
  16. Object.prototype.toString.call(an); // "[object Array]"
  17. ```
  18. 这种方法对于所有基本的数据类型都能进行判断,即使是 `null` 和 `undefined` 。
  19. ```js
  20. Object.prototype.toString.call('An') // "[object String]"
  21. Object.prototype.toString.call(1) // "[object Number]"
  22. Object.prototype.toString.call(Symbol(1)) // "[object Symbol]"
  23. Object.prototype.toString.call(null) // "[object Null]"
  24. Object.prototype.toString.call(undefined) // "[object Undefined]"
  25. Object.prototype.toString.call(function(){}) // "[object Function]"
  26. Object.prototype.toString.call({name: 'An'}) // "[object Object]"
  27. Object.prototype.toString.call() 常用于判断浏览器内置对象时。
  28. ```
  29. 更多实现可见 谈谈 `Object.prototype.toString`
  30.  
  31. 2. `instanceof`
  32. `instanceof` 的内部机制是通过判断对象的原型链中是不是能找到类型的 prototype。
  33.  
  34. 使用 `instanceof`判断一个对象是否为数组,`instanceof` 会判断这个对象的原型链上是否会找到对应的 Array 的原型,找到返回 true,否则返回 false。
  35.  
  36. `[] instanceof Array; // true`
  37. 但 instanceof 只能用来判断对象类型,原始类型不可以。并且所有对象类型 instanceof Object 都是 true。
  38.  
  39. `[] instanceof Object; // true`
  40.  
  41. 3. Array.isArray()
  42. 功能:用来判断对象是否为数组
  43.  
  44. `instanceof` 与 `isArray`
  45.  
  46. 当检测Array实例时,`Array.isArray` 优于 `instanceof` ,因为 `Array.isArray` 可以检测出 `iframes`
  47. ```js
  48. var iframe = document.createElement('iframe');
  49. document.body.appendChild(iframe);
  50. xArray = window.frames[window.frames.length-1].Array;
  51. var arr = new xArray(1,2,3); // [1,2,3]
  52.  
  53. // Correctly checking for Array
  54. Array.isArray(arr); // true
  55. Object.prototype.toString.call(arr); // true
  56. // Considered harmful, because doesn't work though iframes
  57. arr instanceof Array; // false
  58. Array.isArray() 与 Object.prototype.toString.call()
  59.  
  60. Array.isArray()是ES5新增的方法,当不存在 Array.isArray() ,可以用 Object.prototype.toString.call() 实现。
  61.  
  62. if (!Array.isArray) {
  63. Array.isArray = function(arg) {
  64. return Object.prototype.toString.call(arg) === '[object Array]';
  65. };
  66. }
  67. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement