「前端每日一问(10)」typeof 与 instanceof 有什么区别?

1,145 阅读3分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

本题难度:⭐

答:

typeofinstanceof 都可以用来判断数据类型

  • typeof 返回一个变量的类型字符串,instanceof 返回的是一个布尔值
  •  typeof 可以判断除了 null 以外的基础数据类型,但是判断引用类型时,除了 function 类型,其他的无法准确判断。
  • instanceof 可以准确地判断各种引用类型,但是不能正确判断原始数据类型。

typeof

typeof 操作符返回一个字符串,表示未经计算的操作数的类型。

typeof 可以精准地判断原始类型,但是不能精准地判断 null 和 引用类型。

引用类型数据,用typeof来判断的话,除了function会被识别出来之外,其余的都输出object

// 数值
typeof 37 === 'number'
typeof 3.14 === 'number'
typeof (42) === 'number'
typeof Math.LN2 === 'number'
typeof Infinity === 'number'
typeof NaN === 'number' // 尽管它是 "Not-A-Number" (非数值) 的缩写
typeof Number(1) === 'number' // Number 会尝试把参数解析成数值

typeof 42n === 'bigint'

// 字符串
typeof '' === 'string'
typeof 'bla' === 'string'
typeof 'template literal' === 'string'
typeof '1' === 'string' // 注意内容为数字的字符串仍是字符串
typeof (typeof 1) === 'string' // typeof 总是返回一个字符串
typeof String(1) === 'string' // String 将任意值转换为字符串,比 toString 更安全

// 布尔值
typeof true === 'boolean'
typeof false === 'boolean'
typeof Boolean(1) === 'boolean' // Boolean() 会基于参数是真值还是虚值进行转换
typeof !!(1) === 'boolean' // 两次调用 ! (逻辑非) 操作符相当于 Boolean()

// Symbols
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'

// Undefined
typeof undefined === 'undefined'
let a
typeof a === 'undefined' // declaredButUndefinedVariable
typeof undeclaredVariable === 'undefined' // undeclaredVariable

// Null
typeof null === 'object' // 历史bug

// 对象
typeof { a: 1 } === 'object'

// 使用 Array.isArray 或者 Object.prototype.toString.call
// 区分数组和普通对象
typeof [1, 2, 4] === 'object'

typeof new Date() === 'object'
typeof /regex/ === 'object' // 正则表达式也是对象

// 下面的例子令人迷惑,非常危险,没有用处。避免使用它们。
typeof new Boolean(true) === 'object'
typeof new Number(1) === 'object'
typeof new String('abc') === 'object'

// 函数
typeof function () {} === 'function'
typeof class C {} === 'function'
typeof Math.sin === 'function'

如果我们想要判断一个变量是否存在,可以使用typeof:(不能使用if(a), 若a未声明,则报错)

if (a) {
  // Uncaught ReferenceError: a is not defined
}

if (typeof a !== 'undefined') {
  // 这样不会报错 
}

instanceof

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

class Person {}

class Student extends Person {

}

const s1 = new Student()

s1 instanceof Student // true
s1 instanceof Person  // true
s1 instanceof Object  // true

当然也可以用来判断类型,不过一定要判断对象实例的时候才是正确的。

const simpleStr = 'This is a simple string'
const myString = new String()
const newStr = new String('String created with constructor')

simpleStr instanceof String // false, 非对象实例,因此返回 false,无法判断原始类型
myString instanceof String // true
newStr instanceof String // true

使用 instanceof 可以精准地判断引用类型。

[] instanceof Array   // true

const fn = function() {}
fn instanceof Function // true

const date = new Date()
date instanceof Date   // true

const re = new /abc/
re instanceof RegExp   // true

结尾

如果我的文章对你有帮助,你的👍就是对我的最大支持^_^

我是阿林,输出洞见技术,再会!

上一篇:

「前端每日一问(9)」0.1 + 0.2 为什么不等于 0.3?如何解决?

下一篇:

「前端每日一问(11)」JS 如何精准地判断数据类型?