Skip to content
此页目录
本文总阅读量

JavaScript 数据类型检测

typeof

  • 基本数据类型适用,引用数据类型会检测成 object

  • typeof 会返回字符串

  • "undefined"表示值未定义;

  • "boolean"表示值为布尔值;

  • "string"表示值为字符串;

  • "number"表示值为数值;

  • "object"表示值为对象(而不是函数)或null;

  • "function"表示值为函数;

  • "symbol"表示值为符号。

js
String ----> string
Number ----> number
NaN   ----> number
Boolean ----> boolean
undefined----> undefined
null  -----> object
Object -----> object
Array  -----> object
function-----> function

typeof typeof 123 // string

// typeof 是一个操作符而不是函数,所以不需要参数(但可以使用参数)。
typeof 'message' // "string"
typeof('message') // "string"
typeof null // "object" 这是因为特殊值null 被认为是一个对空对象的引用

instanceof

  • 根据原型链来识别返回 true 或 false
js
person instanceof Object // 变量person是Object吗
person instanceof Array // 变量person是Array吗
// 所有引用值都是属于 Object 下的实例,因此任何引用值都会返回 true

细节

typeof在监测函数时会返回function。 但在safari 5之前和chrome 7之前监测正则表达式时,实现的细节不同,导致也会返回function,因为在这之前正则的内部实现了[[call]]方法。 因为ECMA-262规定内部实现了[[call]]方法的对象,typeof时都返回function。 在IEFirefox中则会返回Object

判断是否是数组

js
let arr = [];

arr instanceof Array // true
arr.constructor === Array // true
arr.__proto__ === Array.prototype // true
Array.isArray(arr) // true
Object.prototype.toString.call(arr) // '[object Array]'
Array.prototype.isPrototypeOf(arr)// true

Object.toString 判断

  • 利用顶级对象 toString 方法改变 this 指向判断数据类型
js
Object.prototype.toString.call([])// [object Array]
Object.prototype.toString.call(2)// [object Number]
Object.prototype.toString.call(Function)// [object Function]

Undefined 类型

当使用var 或let 声明了变量但没有初始化时,就相当于给变量赋予了undefined 值

js
let message; // undefined
console.log(message == undefined); // true
console.log(age); // 报错,没有声明

// 对未声明的变量,只能执行一个有用的操作,就是对它调用typeof
console.log(typeof age); // "undefined" 未声明
// 所以初始化的时候赋值,typeof 来检查某个变量是否未声明

// 未声明的变量调用 delete 也不会报错
delete a

Null 类型

null 值表示一个空对象指针,typeof null 会返回"object"

js
console.log(typeof null); // "object"

使用 null 来初始化对象,只需要判断是不是null就可以知道是否被赋值引用

js
let car = null;
if (car != null) {
  // 一些操作
}

undefined 值是由null 值派生而来的,因此ECMA-262 将它们定义为表面上相等

js
console.log(null == undefined); // true 
//(==)比较null 和undefined 始终返回true

评论

交流群