JS 判断数组的6种方式
date
Dec 27, 2023
slug
six-ways-to-make-sure-type-of-array
status
Published
tags
Interview
summary
six ways to make sure type of array
type
Post
首先定义一个
arr, let arr = []方式一: 通过instanceof 判断
instanceof 是判断某个构造函数的原型 prototype 是否在某个实例对象的原型链上
console.log( a instanceof Array ) // true
方式二:通过constructor 判断
实例对象的 constructor 指向它的构造函数本身
console.log( a.constructor === Array ) // true
方式三: ES6 通过Array.isArray()方法判断
console.log( Array.isArray(a) ) // true
方式四: 通过isPrototypeOf 方法判断
isPrototypeOf 方法用于检测某个对象是否在某个实例对象的原型链上
console.log( Array.prototype.isPrototypeOf(a) ) //true
方式五: 通过Object.prototype.toString.call() 方法判断
Array 继承自 Object, 所有他也有toString 方法,但是它重写了toString 方法
console.log( Object.prototype.toString.call(a) === '[object Array]' ) // true
方式六:通过getPrototypeOf 方法判断
getPrototypeOf 方法返回指定对象的原型
console.log( Object.getPrototypeOf(a) === Array.prototype ) // true