typeof与instenceof

在 JS 处理数据的过程中经常会有类型判断的需要,首先我们知道 JS 中的的 6 种基本数据类型:

  1. null:空。表示不纯在;
  2. undefined:未定义,声明变量未赋值时;
  3. number:数值;
  4. string:字符串;
  5. boolean:布尔值;
  6. object:对象。

那么最常见的类型判断方法就是 typeof 和 instenceof。

typeof

typeof 可以用来检测给定变量的数据类型,可能的返回值如下:

1
2
3
4
5
6
7
8
9
10
typeof null; // 'object'
typeof undefined; // 'undefined'
typeof 1; // 'number'
typeof "string"; // 'string'
typeof true; // 'boolean'
typeof {}; // 'object'
typeof []; // 'object'
typeof function () {}; // 'function'
var a;
typeof a; // 'undefined'

通过上面的代码,我们可以发现 typeof 不能判断出 null 和 object。所以不要使用 typeof 判断 null 和 object,可以直接用==判断 null;

1
2
3
if (a == null) {
//do something
}

instanceof

instanceof 常用于判断一个变量是否是某个对象的实例,是一个三元运算符与 typeof 的实质区别

1
2
3
4
5
6
//用法

object instanceof constructor

var o = {};
o instenceof Object; //true

我随便写封装了一个判断类型的函数

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* 这是一个判断类型的函数,返回布尔值
*/

var type = {
// 判断是否为null
isNull: function (input) {
if (input === null) {
return true;
} else {
return false;
}
},

// 判断是否为undefined或者以声明未赋值
isUndefined: function (input) {
if (typeof input === "undefined") {
return true;
} else {
return false;
}
},

// 判断是否为数字
isNum: function (input) {
if (typeof input === "number") {
return true;
} else {
return false;
}
},

// 判断是否为字符串
isStr: function (input) {
if (typeof input === "string") {
return true;
} else {
return false;
}
},

// 判断是否为函数
isFun: function (input) {
if (typeof input === "function") {
return true;
} else {
return false;
}
},

// 判断是否为数组
isArr: function (input) {
if (Array.isArray(input)) {
return true;
} else {
return false;
}
},

// 判断是否为对象【注意:数组,null也是对象】
isObj: function (input) {
if (typeof input === "Object" && input instanceof Object) {
return true;
} else {
return false;
}
},
};

[越努力,越幸运!]