飞跃高山与大洋的鱼飞跃高山与大洋的鱼
首页
先看
计算机
  • 数学
  • Linux
  • Arch
  • Manjaro
  • Ubuntu
  • CentOS
  • Kubernetes
  • Web
  • JavaScript
  • TypeScript
  • CSS
  • Canvas
  • Vue
  • Vite
  • NuxtJS
  • Webpack
  • Flutter
  • D3
  • Jest
  • WeApp
  • Utils
  • Nodejs
  • Nestjs
  • Golang
  • Nginx
  • Traefik
  • MySQL
  • MongoDB
  • Redis
  • Docker
算法
  • 像素风
  • Git
  • Github
  • VSCode
  • Chrome
  • Google
  • Bookmark scripts
  • 导航 🎉
  • VuePress 侧边栏插件
  • VuePress 官网
🚇 开往
首页
先看
计算机
  • 数学
  • Linux
  • Arch
  • Manjaro
  • Ubuntu
  • CentOS
  • Kubernetes
  • Web
  • JavaScript
  • TypeScript
  • CSS
  • Canvas
  • Vue
  • Vite
  • NuxtJS
  • Webpack
  • Flutter
  • D3
  • Jest
  • WeApp
  • Utils
  • Nodejs
  • Nestjs
  • Golang
  • Nginx
  • Traefik
  • MySQL
  • MongoDB
  • Redis
  • Docker
算法
  • 像素风
  • Git
  • Github
  • VSCode
  • Chrome
  • Google
  • Bookmark scripts
  • 导航 🎉
  • VuePress 侧边栏插件
  • VuePress 官网
🚇 开往
  • JAVASCRIPT

    • JavaScript
    • 语句和表达式
    • 数组空位
    • 无法访问 undefined、null 的属性
    • currying
    • 装饰器 Decorator
    • ES6 的简单使用
    • Error 类型
    • 事件队列
    • 隐式转换
    • 调用表达式
    • 函数调用
    • 运算符优先级
    • 原型链
    • 正则 exec
    • 作用域与闭包
    • 一步步启用 babel7
    • 什么是 this
    • typeof
      • 示例
      • 注意事项
        • 1. new 操作符
        • 2. 安全操作
    • 全局属性 undefined
    • 自增/减

typeof

typeof 操作符会返回数据类型的字符串。

JavaScript 数据类型分为原始类型(值类型)和引用类型,其中原始类型包含:Number、String、Boolean、Undefined、Null、Symbol、BigInt(以后可能还会扩展)。

示例

typeof 1 // "number"
typeof "1" // "string"
typeof true // "boolean"
typeof aaa // "undefined"
typeof null // "object"
typeof Symbol("1") // "symbol"
typeof 42n // "bigint"

typeof {} // "object"
typeof [] // "object"
typeof new Date() // "object"
typeof /regex/ // "object"
typeof new Map() // "object"

typeof function() {} // "function"
typeof class App {} // "function"

综上 typeof 可以得到除 Null 之外的所有原始类型,后续再追加原始类型也一样;对于所有的引用类型可以识别出 "function",其余不再细分统一为 "object"。

注意事项

1. new 操作符

new 操作符不总是返回 "object"。

typeof new String("123") // "object"
typeof new Number(123) // "object"

typeof new Function("console.log('hello world')") // "function"

2. 安全操作

在以往 typeof 总是能对任何操作的数据返回一个字符串,所以常常利用其该特性进行判断是否为 undefined,在加入块级作用域后,该特性失效。

typeof aaa // Uncaught ReferenceError: Cannot access 'aaa' before initialization

const aaa = "hello world";
编辑文档!
上次更新:
贡献者: shanyuhai123
Prev
什么是 this
Next
全局属性 undefined