JS

如何判断对象是Array类型

2019-09-18  本文已影响0人  匆匆那年_海

1.使用instanceof方法:

instanceof 用于判断一个变量是否为某个对象的实例。原理是通过判断操做对象的原型链上是否具有构造函数的prototype属性。

eg:
var arr=[1,2,3];
console.log(arr instanceof Array) //true

2.constructor 返回对象相对应的构造函数。

eg:
console.log([1,2,3].constructor == Array);  //true
console.log({}.constructor == Object);  //true
console.log("string".constructor == String); //true
console.log((123).constructor == Number);  //true
console.log(true.constructor == Boolean);  //true

3.使用Object.prototype.toString.call(arr) === '[object Array]'

eg:
console.log(Object.prototype.toString.call([1,2,3]));  //[object Array]
console.log(Object.prototype.toString.call({}));  //[object Object]
console.log(Object.prototype.toString.call(function () {}));  //[object Function]

4.ES5定义了Array.isArray()

eg:
Array.isArray([1,2,3]) //true

原文作者:匆匆那年_海,博客主页:https://www.jianshu.com/u/910c0667c515
95后前端汉子,爱编程、优秀、聪明、理性、沉稳、智慧的程序猿一枚。

上一篇 下一篇

猜你喜欢

热点阅读