在js中, 有两种数据类型,基本类型和引用类型
基本类型: Number
、String
、Undefined丶B
oolean丶N
ull丶Symbol
引用类型:Array丶Object丶Function
判断类型的常用方法:
1丶typeof: 返回数据的数据类型,Null
、Array丶Object丶Function
来说,使用typeof
都会统一返回object
字符串
2丶Object.prototype.toString.call(): 方法返回一个表示该对象的字符串。
3丶instanceof : 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型(_proto_)中, 运算符希望左操作数是一个对象,右操作数标识对象的类。如果左侧对象是右侧类的实例,则表达式返回为true,否则返回false。
判断number
、string
、undefined丶
boolean
的方法:
Object.prototype.toString.call(123) // "[object Number]"
Object.prototype.toString.call(“abc”) // "[object String]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(true) // "[object Boolean]"
typeof 123 // "number"
typeof "" // "string"
typeof undefined // "undefined"
typeof true // "boolean"
判断数组的方法:
var arr = []
Object.prototype.toString.call(arr) //"[object Array]"
arr instanceof Array // true
Array.isArray(arr) //true
当检测Array实例时,
Array.isArray
优于instanceof,因为Array.isArray能检测iframes
.var iframe = document.createElement('iframe'); document.body.appendChild(iframe); xArray = window.frames[window.frames.length-1].Array; var arr = new xArray(1,2,3); // [1,2,3] // Correctly checking for Array Array.isArray(arr); // true // Considered harmful, because doesn't work though iframes arr instanceof Array; // false
判断对象的方法:
var obj = {}
Object.prototype.toString.call(arr) //"[object Object]"
typeof obj //"object"
obj instanceof Object // true
判断函数的方法:
var fun = function() {
console.log('test')
}
Object.prototype.toString.call(fun) //"[object Function]"
typeof fun //"function"
fun instanceof Function // true