重学javascript之如何识别数组

当面试被问到如何区分数组的时候,我想不少基础不扎实的同窗第一时间想到的是typeof,可是typeof对于数组是不可行的,由于数组属于对象es6

let myArray = ['banner','apple','orange']
typeof(myArray)        //Object复制代码

识别数组的方法以下面试

一、使用es6提供的Array.isArray()方法数组

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

二、建立本身的isArray()函数来识别bash

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

let myArray = ['banner','apple','orange']
isArray(myArray)            //true复制代码

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

三、假如对象是由给定的构造器建立,则instanceof运算符返回true函数

let myArray = ['banner','apple','orange']
myArray instanceof Array     //true复制代码

为true则是数组ui

相关文章
相关标签/搜索