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