isArray()方法是ES5新增的用于判断一个对象是否为数组;如果对象是数组返回true,否则返回false。
Array.isArray(["Banana", "Orange", "Apple", "Mango"])
// true
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
["Banana", "Orange", "Apple", "Mango"] instanceof Array
// true
注意: instanceof 只能用来判断对象类型,不适合判断原始类型。
1 instanceof Number
// false
'teststr' instanceof String
//false
该方法可以很好地区分各种类型,甚至是 null 和 undefined , 除了自定义对象类型(这个可用instanceof区分)。
Object.prototype.toString.call(["Banana", "Orange", "Apple", "Mango"])
// [object Array]
Q1: 为什么不直接用toString()
先看一下toString()的结果
["Banana", "Orange", "Apple", "Mango"].toString()
// 'Banana,Orange,Apple,Mango'
由于toString 是 Object的原型方法,类似Array、Function等具体类型作为Object的实例,已经重写了toString 方法。那么根据原型链知识:Array类型返回元素组成的字符串,如结果所示。
所有对象(使用 Object.create(null) 创建的对象除外)都将具有 constructor 属性。在没有显式使用构造函数的情况下,创建的对象(例如对象和数组文本)将具有 constructor 属性,这个属性指向该对象的基本对象构造函数类型。
constructor 属性返回 Object 的构造函数(用于创建实例对象)。注意,此属性的值是对函数本身的引用,而不是一个包含函数名称的字符串。
const o = {}
o.constructor === Object // true
const o = new Object
o.constructor === Object // true
const a = []
a.constructor === Array // true
const a = new Array
a.constructor === Array // true
const n = new Number(3)
n.constructor === Number // true
["Banana", "Orange", "Apple", "Mango"].constructor==Array
// true
答案:不可以
原因:
typeof 对原始数据类型
(null除外)都可以显示为正确的类型
typeof 对对象
(函数除外),都会显示object
如:typeof [1, 2, 4] == 'object'; // true typeof new Date() === 'object'; // true typeof /regex/ === 'object'; // true typeof null === 'object'; // true