判断数据类型:typeof和instanceof

(1)typeof

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

console.log(typeof '');//string
console.log(typeof []);//object
console.log(typeof {});//object
console.log(typeof 1);//number
console.log(typeof null);//object
console.log(typeof undefined);//undefined
console.log(typeof true);//boolean
console.log(typeof function(){});//function
console.log(typeof /\d/);//object

(2)instanceof

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

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


(3)Object.prototype.toString

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

var type=Object.prototype.toString
console.log(type.call(''));//object String
console.log(type.call([]));//object Array
console.log(type.call({}));//object Object
console.log(type.call(false));//object Boolean
console.log(type.call(null));//object Null
console.log(type.call(undefined));//object Undefined
console.log(type.call(function(){}));//object Function
判断方式

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




你可能感兴趣的:(JavaScript)