In many cases I have to do different processing for different types of data
First, let's look at the data types
In JavaScript, data types are divided into two categories: basic types and reference types
basic type
Underfine Uull Number String Boolean
Check if it is a primitive type
typeof will do it
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
|
reference type
Reference types are usually called classes, that is, when a reference value is encountered, the object is handled.
Object Function Array and other objects.
From the last n and o above, we know that typeof can only check out an object. Usually, what is the type of data we need, and instanceof appears here .
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]
|
Through the above method, we can check all data types