数据类型判断

151 阅读2分钟

typeof

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

let num = 100;
typeof num; // number
typeof NaN; // number

let str = 'abc';
typeof str; // string

let bool = true;
typeof bool; // boolean

let sym = Symbol(123);
typeof sym; // symbol

let und = undefined;
typeof und; // undefined

let big = BigInt(100);
typeof big; // bigint

// ================= //
let foo = function() {};
typeof foo; // function

// ================= //
let date = new Date();
let nul = null;
let arr = [1,2,3];
let reg = new RegExp(/\s+/g);
typeof nul; // object
typeof date; // object
typeof arr; // object
typeof reg; // object

typeof Math; // object

  • 对于除null之外基本类型Function,使用typeof可以准确的判断除数据的类型
  • 对于null, 在 JavaScript 最初的实现中,JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是 0。由于 null 代表的是空指针(大多数平台下值为 0x00),因此,null 的类型标签是 0,typeof null 也因此返回 object
  • 其它的引用类型,包括(Object, Array, RegExp, Date...)使用typeof都会返回 object
  • 尽管NaNNot-A-Number (非数值) 的缩写, 使用typeof检测仍然会返回number

instance of

用于检测某个构造函数的prototye属性是否出现在实例的原型链上

let num = new Number(123);
num instanceof Number; // true
num instanceof Object; // true

let arr = new Array(1,2,3,4);
arr instanceof Array; // true
arr instanceof Object; // true

let obj = {a: 123};
obj instanceof Object; // true

let date = new Date();
date instanceof Date; // true
date instanceof Object; // true

let set = new Set([1,2,3]);
set instanceof Set; // true
set instanceof Array; // false
set instanceof Object; // true

Math instanceof Object; // true
  • 所有的引用类型的原型链最终都会指向到Object

最准确的判断类型的方法

function getType(value) {
    return Object.prototype.toString.call(value);
}

let num = 1;
let num1 = new Number(123);

getType(num); // '[object Number]'
getType(num1); // '[object Number]'

let str = 'abc';
let str1 = new String('aaa');

getType(str); // '[object String]'
getType(str1); // '[object String]'

let nul = null;
let und = undefined;

getType(unl); // '[object Null]'
getType(und); // '[object Undefined]'

let date = new Date();
getType(date); // '[object Date]'
...

  • 使用Object.prototype.toString.call(val)可以检测出数据的最终类型