JS检测数组类型的四种方法!!!

141 阅读2分钟

「这是我参与2022首次更文挑战的第9天,活动详情查看:2022首次更文挑战」。

typeof

typeof是一个操作符,用法有两种 1、typeof(检测类型)2、typeof 检测类型

typeof不是一个对象,所以加()不是必需的,下面是检测的所有类型,下面🌰,我们会发现typeof会检测到基本数据类型,也可以检测出是一个函数,但是在检测引用数据类型的时候却无法检测到是属于那一类

typeof 1 // number
typeof ‘’ // string
typeof true // boolean
typeof undefined // undefined
typeof function(){} //fnction
typeof {} //object
typeof null // object null在js里面是空对象的指针,所以是object
typeof [] // object

instanceof

instanceof是一个操作符,返回值是一个布尔值,用途是检测引用数据类型的,基本数据类型检测不了,不信咱就看看下面的🌰

基本数据类型
console.log(1 instanceof Number) // false
console.log("" instanceof String) // false
console.log(false instanceof Boolean) // false
引用数据类型
console.log([] instanceof Array) // true
console.log({} instanceof Object) // true
console.log(function(){} instanceof Function) // true

上面的引用数据类型检测出来的没有问题,但是基本数据类型检测的,看着也没错呀,怎么就false了呢,别慌,我们采用new创建一个基本数据类型试试看

console.log(new Number(1) instanceof Number) // true
console.log(new String("") instanceof String) // true
console.log(nwe Boolean(false) instanceof Boolean) // true

constructor

constructor存在于构造函数的原型上,指向构造函数,对象可以通过__proto__在所属的类上找到这个属性,返回值是一个布尔值

console.log(('1').constructor === String) // true
console.log((1).constructor === Number) // true
console.log((false).constructor === Boolean) // true
console.log(([]).constructor === Array) // true
console.log(({}).constructor === Object) // true
console.log((function(){}).constructor === Function) // true

上面的🌰,看起来这个方法用来检测基本数据类型或者引用数据类型都没有问题,但是此处出现一个小疑问,因为constructor这个方法是在构造函数的原型上,如何出现的继承会怎么办呢? 看下一个🌰

fnc(){ // fnc此刻是一个函数
}
fuc.prototype = new Array() //把构造函数的原型指向Array的原型
const fnc = new fnc()
console.log(fnc.constructor === Array) // true

Object.prototype.toString.call()

返回值是一个数组,这个方法可以检测任意类型,哪怕修改了原型,检测出来的还是最初始的类型

console.log(Object.prototype.toString.call(1)) //[object Number]
console.log(Object.prototype.toString.call('')) //[object String]
console.log(Object.prototype.toString.call(true)) //[object Boolean]
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call([])) // [object Array]
console.log(Object.prototype.toString.call({})) // [object Object]
console.log(Object.prototype.toString.call(/^$/)) //[object RegExp]
console.log(Object.prototype.toString.call((function () {}))) //[object Function]
const obj = {name: "waniz"age: 21}
console.log(obj.toString()) // [Object, Object]

在上面的🌰中,可以看到,要先获取Object原型上的toString方法,并且改变方法中this的指向,Object.prototype.toString的作用是返回当前方法的执行体,toString中的thisobj,返回是obj的所属信息,[Object, Object]返回的数组中,第一个参数是固定的,指的是当前实例是对象数据类型的,第二个参数是obj所属的类是objecttoString中的thisMath,所以返回Math所属类的信息是[Object, Object]

今天学习一点点🤏🏻,下期再见