927   JS

JS 可以通过 typeof 来判断数据类型

var a="a";
typeof a // string
var b=1;
typeof b // number
var c=false;
typeof c // boolean
var d;
typeof d //undfined

var nul=null
typeof // object
var arr=[1] 
typeof arr; // object
var obj={"k":"v"}
typeof obj // object

然后发现,null,数组,对象都返回了 object,说明用 typeof 是有缺陷的
考虑使用 instanceof

[] instanceof Array // 正常 true
null instanceof Object // 结果是 false

instanceof 也有缺陷

Object.prototype.toString方法返回对象的类型字符串,因此可以用来判断一个值的类型

Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call([]) // "[object Array]"

使用 call 是因为 String Number等数据类型会重写toString的方法,通过 call 可以调用父类即继续对象 Object 的 toString

对于数组等类型的判断,有更简洁的方法
如果你使用 JQ

$.isArray([])

ES5 让你愉快

Array.isArray([])



Leave a Reply

Your email address will not be published. Required fields are marked *