首页 > 代码库 > js 判断数据类型

js 判断数据类型

var a = {};
var b = [];
var c = null;
var d = ‘‘;
var e = undefined;

var aa = (typeof a === ‘object‘);
var bb = (typeof b === ‘object‘);
var cc = (typeof c === ‘object‘);
var dd = (typeof d === ‘object‘);
var ee = (typeof e === ‘object‘)

var f = [aa,bb,cc,dd,ee];

console.log(f);

>: [true, true, true, false, false]

var aa = (typeof a === ‘object‘); 
var bb = (typeof b === ‘object‘); 
var cc = (typeof c === ‘object‘); 
var dd = (typeof d === ‘string‘); 
var ee = (typeof e === ‘undefined‘)

var f = [aa,bb,cc,dd,ee];

console.log(f);

>: [true, true, true, true, true]

推论:‘’及undefined的typeof不是Object,而是string及undefined类型

var aa = a instanceof Object;
var bb = b instanceof Object;
var cc = c instanceof Object;
var dd = d instanceof Object;
var ee = e instanceof Object;

var f = [aa,bb,cc,dd,ee];

console.log(f);

>: [true, true, false, false, false]

var aa = a instanceof Object; 
var bb = b instanceof Object; 
var cc = c instanceof Object; 
var dd = d instanceof Object; 
var ee = e instanceof Object; 

var f = [aa,bb,cc,dd,ee];

console.log(f);

>: [true, true, false, false, false]

console.log(c instanceof null)
>: 抛出错误

console.log(d instanceof String)

>: false

console.log(new String(‘123‘) instanceof String)

>: true

console.log(e instanceof undefined)

>: false

推论:instanceof 仅用于判断对象是否属于指定对象的实例,null不是任何对象的实例;简单数据类型如bool、number、string、undefined均不是其他对象的实例,因此不能使用instanceof运算符判断,但是,显式的使用基本包装类型创建的对象则可以使用instanceof判断出具体类型;

var aa = a.constructor.name;
var bb = b.constructor.name;
var cc = c.constructor.namet;
var dd = d.constructor.name;
var ee = e .constructor.name;
var f = [aa,bb,cc,dd,ee];
console.log(f);

>:["Object", "Array", 错误, "String", 错误]

错误都是因为null和undefined并无构造子引起的;

 

js 判断数据类型