JS判断对象/数组

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之前不支持

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。