JS判断对象/数组

作者: Allan要做活神仙 | 来源:发表于2019-05-16 14:47 被阅读0次

2019-05-16-14:39:于公司

var a = function(){};
var b = [];

用JS怎么知道他们是什么类型?

最佳 Object.prototype.toString.call()

Object.prototype.toString.call(a)  // "[object Function]"
Object.prototype.toString.call(b)  // "[object Array]"

typeof

typeof a // "function"
typeof b // "object"

除了array和null判断为object外,其他的都可以正常判断

constructor

a.constructor  // ƒ Function() { [native code] }
b.constructor  // ƒ Array() { [native code] }

instanceof

数组判断

b instanceof Array  // true

Array.isArray()

Array.isArray(b)   // true

ie8之前不支持

相关文章

网友评论

    本文标题:JS判断对象/数组

    本文链接:https://www.haomeiwen.com/subject/axdiaqtx.html