判斷數組類型的4種方法


 1 /**  2  對數組類型的判斷  3 */
 4 
 5 var n=1,  6       s='hello',  7       b=true,  8       un=undefined,  9       nu=null,  10       fun=function () {};  11 console.log(n+'類型是:'+typeof n);  12 console.log(b+'類型是:'+typeof b);  13 console.log(un+'類型是:'+typeof un);  14 console.log(nu+'類型是:'+typeof nu);  15 console.log(fun+'類型是:'+typeof fun);  16 /*
 17  1類型是:number  18  true類型是:boolean  19  undefined類型是:undefined  20  null類型是:object  21  function () {}類型是:function  22 * */
 23 
 24 /*
 25 typeof 只能用於區分5種原始類型(number\string\boolean\null\undefined)和函數function,  26 無法用於區分內置對象類型  27 */
 28 
 29 /*
 30 * 原型對象:集中存儲同一類型的子對象所需的所有共有屬性和方法的父對象。在定義構造函數的時候自動創建原型對象。  31 * 構造函數類型名.prototype == 父類型原型對象 == 子類型原型對象.__proto__  32 * */
 33 
 34 var obj1=[1,2,3],  35     obj2={},  36     obj3={},  37     obj4=function () {},  38     obj5={};  39 
 40 obj3.__proto__ = Array.prototype;  41 obj5.__proto__ = obj1; // obj5-->obj1-->Array.prototype
 42 
 43 console.log('obj1類型是: '+typeof obj1);  44 console.log('obj2類型是: '+typeof obj2);  45 console.log('obj4類型是: '+typeof obj4);  46 
 47 console.log('obj3類型是: '+typeof obj3);  48 console.log('obj5類型是: '+typeof obj5);  49 /*
 50  obj1類型是: object  51  obj2類型是: object  52  obj4類型是: function  53 
 54  obj3類型是: object  55  obj5類型是: object  56 * */
 57 /**  58 4種用於判斷數組類型的方法:  59  第一種:var bool = father.isPrototypeOf(child)---該方法判斷比較松散  60  第二種:var bool = child instanceof Array---該方法判斷比較松散  61  第三種:判斷對象內部屬性class---該方法判斷比較嚴格  62  第四種:ES5: Array.isArray(obj)----該方法判斷比較嚴格
 63 **/  
64
// 第一種:var bool = father.isPrototypeOf(child)
65
console.log(
66
  Array.prototype.isPrototypeOf(obj1),
67
  Array.prototype.isPrototypeOf(obj2),
68
  Array.prototype.isPrototypeOf(obj3),
69
  Array.prototype.isPrototypeOf(obj4),
70
  Array.prototype.isPrototypeOf(obj5),
71
);
72
// result:true false true false true
73

74

75
// 第二種:var bool = child instanceof Array
76
console.log(
77
  obj1 instanceof Array,
78
  obj2 instanceof Array,
79
  obj3 instanceof Array,
80
  obj4 instanceof Array,
81
  obj5 instanceof Array,
82
);
83
// result:true false true false true
84

85
// 第三種:判斷對象內部屬性class
86
console.log(
87
  Object.prototype.toString.call(obj1) == '[object Array]',
88
  Object.prototype.toString.call(obj2) == '[object Array]',
89
  Object.prototype.toString.call(obj3) == '[object Array]',
90
  Object.prototype.toString.call(obj4) == '[object Array]',
91
  Object.prototype.toString.call(obj5) == '[object Array]'
92
);
93
// result:true false false false false
94

95
// 第四種:ES5: Array.isArray(obj)
96
console.log(
97
  Array.isArray(obj1),
98
  Array.isArray(obj2),
99
  Array.isArray(obj3),
100 Array.isArray(obj4),
101 Array.isArray(obj5),
102 );
103 // result:true false false false false 104   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM