码迷,mamicode.com
首页 > Web开发 > 详细

js 判断数据类型

时间:2016-11-25 23:31:46      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:define   包装   str   创建   使用   var   efi   cto   tor   

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 判断数据类型

标签:define   包装   str   创建   使用   var   efi   cto   tor   

原文地址:http://www.cnblogs.com/SevenDrunk/p/6103081.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!