判断数据类型:typeof和instanceof

来源:互联网 发布:js 分享 编辑:程序博客网 时间:2024/06/15 12:54

(1)typeof

主要用于判断数据是不是基本数据类型String、Number、Object、Null、Undefined,但是无法判断出function(有些浏览器会出错)、array、regExp

console.log(typeof '');//stringconsole.log(typeof []);//objectconsole.log(typeof {});//objectconsole.log(typeof 1);//numberconsole.log(typeof null);//objectconsole.log(typeof undefined);//undefinedconsole.log(typeof true);//booleanconsole.log(typeof function(){});//functionconsole.log(typeof /\d/);//object

(2)instanceof

主要的目的是用来检测引用类型,判断ArrayRegExp,无法准确判断Function

console.log([] instanceof Array);//trueconsole.log({} instanceof Object);//trueconsole.log(/\d/ instanceof RegExp);//trueconsole.log(function(){} instanceof Object);//trueconsole.log(function(){} instanceof Function);//true
console.log('' instanceof String);//falseconsole.log(1 instanceof Number);//false


(3)Object.prototype.toString

折是对象的一个原生原型扩展函数,用来精确的区分数据类型

var type=Object.prototype.toStringconsole.log(type.call(''));//object Stringconsole.log(type.call([]));//object Arrayconsole.log(type.call({}));//object Objectconsole.log(type.call(false));//object Booleanconsole.log(type.call(null));//object Nullconsole.log(type.call(undefined));//object Undefinedconsole.log(type.call(function(){}));//object Function
判断方式

console.log(type.call('')=="[object String]");//true
其他的以此类推




阅读全文
0 0
原创粉丝点击