检测数据类型的几种方式

时间:2017-10-24 13:03:40   收藏:0   阅读:234

JS中检测数据类型只有四种方式

  [typeof value]

1)返回值:首先是一个字符串,然后包含了我们常用的数据类型,例如:"number"、"string"、"boolean"、"undefined"、"object"、"function"
typeof typeof typeof [12] -> "string"
2)typeof null ->"object" 因为null是一个空对象指针
3)typeof不能具体的细分对象、数组、正则等,因为不管检测哪一个返回的都是"object"
var ary=[];
ary instanceof Array ->true
ary instanceof RegExp ->false
ary instanceof Object ->true 所有的对象都是Object这个基类的一个实例
ary.constructor===Array ->true 说明ary是Array这个类的一个实例(constructor可以让用户自己来修改,所有我们一般不用这个来检测)

在类的继承中,我们只是单纯通过instanceof来检测数据类型的话是不准确的
[案例]

function Fn() {this.x=100;}
Fn.prototype = new Array;
var f = new Fn;
//f只是继承了数组中常用的方法,但是不是数组,例如:在梨树上嫁接苹果树,苹果树只是继承使用了梨树的水分和营养,但是长出来的果实还是苹果而不是梨
//console.log(f instanceof Fn);//->true
//console.log(f instanceof Array);//->true
//console.log(f instanceof Object);//->true

var oDiv=document.getElementById("div1");
//oDiv->HTMLDivElement->HTMLElement->Element->Node->EventTarget->Object
console.log(oDiv instanceof EventTarget);//->true
//Object.prototype.toString() ->返回的是 Object.prototype 的数据类型 ->"[object Object]"
//f.toString() ->返回的是f的数据类型 ->"[object Object]"
Object.prototype.toString.call(12) ->检测12的数据类型 ->"[object Number]"
Object.prototype.toString.call("zhufeng") ->"[object String]"
Object.prototype.toString.call(null) ->"[object Null]"
Object.prototype.toString.call(undefined) ->"[object Undefined]"
Object.prototype.toString.call([]) ->"[object Array]"
Object.prototype.toString.call(/^$/) ->"[object RegExp]"
Object.prototype.toString.call(function(){}) ->"[object Function]"

 

原文:http://www.cnblogs.com/Scar007/p/7722881.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!