常见判断是对象还是数组的4种方法

1.constructor

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var obj={}

function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}

console.log(isArray(fruits)) //true
console.log(isArray(obj)) //false

 

 2.Object.prototype.toString

console.log(Object.prototype.toString.call(fruits)); //[object Array]

3.instanceof  //判断fruits的原型链上有没有Array的原型

console.log(fruits instanceof Array) //true

 4.isArray

 

Array.isArray(fruits);

  

posted @ 2020-07-16 11:23  菜鸟程序员的总结  阅读(749)  评论(0编辑  收藏  举报