读JavaScript高级程序设计之js中如何判断类型

在很多情况下我都要对不同类型的数据做不同的处理

首先我们看看数据类型有那些

在JavaScript中数据类型分为2大类 基本类型 和 引用类型

基本类型

Underfine Uull Number String Boolean

检查是否是基本类型

typeof 就能搞定

 
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
     
var s = 'string';
var b = false;
var i = 1;
var u;
var n = null;
var o = new Object();
console.log( typeof s);
console.log( typeof b);
console.log( typeof i);
console.log( typeof u);
console.log( typeof n);
console.log( typeof o);
//string
//boolean
//number
//undefined
//object
//object

引用类型

引用类型通常叫做类(class),也就是说,遇到引用值,所处理的就是对象。
Object Function Array 等对象。

从上面最后 n 和 o 我们知道typeof 只能检查出是一个对象,通常情况下我们跟需要数据的类型是什么,这里就出现了 instanceof

instanceof

 
     
1
2
3
4
5
6
7
8
9
10
11
12
 
     
var o = new Object();
var a = [ 1, 2, 3];
var c = function (){};
o instanceof Object
a instanceof Array
c instanceof Function
//true
//true
//true

instanceof 后面一定要是对象类型,并且是大写

根据对象的constructor进行判断

 
     
1
2
3
4
5
6
7
8
9
10
11
 
     
var o = new Object();
var a = [ 1, 2, 3];
var c = function (){};
o.constructor === Object
a.constructor === Array
c.constructor === Function
//true
//true
//true

当constructor 在类继承时就会出错(prototype)

 
     
1
2
3
4
5
6
7
8
9
 
     
function p1(){}
function p2(){}
p1.prototype = new p2();
var p = new p1();
p.constructor === p1; //false
p.constructor === p2; //true

之所以是这样,是因为p1是继承自p2的原型链构造函数到了p2,如果想纠正需要将自己的类型赋值给对象的constructor,这里我们new 的是 p1 p.constructor = p1.

通常情况下我们不会这么复杂的去运用函数。

有一个复杂的方法 prototype

prototype : 能给出具体的类型,然后通过字符串方式进行判断

 
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 
     
var s = 'string';
var b = false;
var i = 1;
var u;
var n = null;
var o = new Object();
var c = function(){};
console.log( Object.prototype.toString.call(s));
//[object String]
console.log( Object.prototype.toString.call(b));
//[object Boolean]
console.log( Object.prototype.toString.call(i));
//[object Number]
console.log( Object.prototype.toString.call(u));
//[object Undefined]
console.log( Object.prototype.toString.call(n));
//[object Null]
console.log( Object.prototype.toString.call(o));
//[object Object]
console.log( Object.prototype.toString.call(c));
//[object Function]

通过以上的方法我们就能对全部的数据类型进行检查

猜你喜欢

转载自blog.csdn.net/wang252949/article/details/80017476