typeof 类型判断

前言

我们可以试着打印一下数组的 typeof ,会看到他们的类型都是 object 而不是 array

console.log(typeof(new Array()));
console.log(typeof([]));

在这里插入图片描述

分析

  • typeof 可以返回的类型为:number、string、boolean、undefined、object、function

在 ECMA 中,除了 Number,String,null,undefined,Boolean,其它的实例都会归为 object。因此 typeof 对于检测对象就不靠谱了,不只是Array,javascript中的对象,包括 Date, String, Boolean, Number, Object, Function, Array, RegExp, Error 使用 typeof 只会返回 “object”。

typeof(undefined) // "undefined"
typeof(null) // "object"
typeof([1,2]) // "object"
typeof({
    
    a:1}) // "object"
typeof('123') // "string"
typeof(1) // "number"
typeof(true)  // "boolean"
typeof(Array) // "function"
typeof(() => {
    
    })  // typeof 箭头函数返回也是 "function"
typeof(typeof(null))   // "string"
typeof(typeof(undefined))  // "string"

typeof(undefined) === undefined // false
typeof(undefined) === "undefined" // true

而创建 Function 或者 Array 这些类型的实例的时候,其实都是基于 Object 实例进行的一种扩展。只是多了一些特有属性。判断一个对象是一个数组还是普通的Object可以使用 Array.isArray([])[] instanceof Array 的方法。然而这个方法会因为在跨 iframe 的情况下失效。最简单的办法是 Object.prototype.toString.call(array) 的方式。因为只有通过 Object 的原型的 toString 方法才能拿到每个实例的[class]内部属性。

arr = []
arr instanceof Array // instanceof判断方法
Array.prototype.isPrototypeOf(arr) // 原型链判断
Array.isArray(arr) // JS 数组方法Array中的isArray方法

更深层次的判断在这里暂时不研究

猜你喜欢

转载自blog.csdn.net/qq_53810245/article/details/130850863