重学javascript之如何识别数组

195 阅读1分钟

当面试被问到如何区分数组的时候,我想很多基础不扎实的同学第一时间想到的是typeof,但是typeof对于数组是不可行的,因为数组属于对象

let myArray = ['banner','apple','orange']
typeof(myArray)        //Object

识别数组的方法如下

1、使用es6提供的Array.isArray()方法

let myArray = ['banner','apple','orange']
Array.isArray(myArray)    //true

2、创建自己的isArray()函数来识别

function isArray(x){
    return x.constructor.toString().indexOf('Array') != -1;
}

let myArray = ['banner','apple','orange']
isArray(myArray)            //true

若参数为数组,则会返回true;另一种说法:若对象原型中有Array这个单词,则为true

3、假如对象是由给定的构造器创建,则instanceof运算符返回true

let myArray = ['banner','apple','orange']
myArray instanceof Array     //true

为true则是数组