【JS】数据类型判定

1. typeof相关

基本类型:number string boolean null undefined symbol bigint
非基本类型:function object

console.log(typeof 123);//number
console.log(typeof NaN);//number
console.log(typeof "123");//string
console.log(typeof false);//boolean
console.log(typeof null);//object
console.log(typeof undefined);//undefined
console.log(typeof Symbol("Lawson"));//symbol
console.log(typeof 123n);//bigint
console.log(typeof function(){});//function
console.log(typeof []);//object
console.log(typeof {});//object
function Person(name){
  this.name = name;
}
let p = new Person('Lawson');
console.log(typeof p);//object
console.log(typeof Function);//function
console.log(typeof Object);//function
console.log(typeof String);//function
  • 注意typeof null是object
  • typeof无法准确判定数据类型

2. instanceof相关

构造函数的 prototype 属性是否出现在某个实例对象的原型链上
foo instanceof Foo == true成立条件 foo.__proto__[.__proto__ * n] == Foo.prototype

let myNum = new Number(123);
let myStr = new String('123');
let myBool = new Boolean(false);
let nullObj = Object.create(null);
let curDate = new Date();
let myReg = new RegExp('^\d[.png]$');

console.log(123 instanceof Number);//false
console.log(myNum instanceof Number);//true
console.log(myNum instanceof Object);//true

console.log('123' instanceof String);//false
console.log(myStr instanceof String);//true
console.log(myStr instanceof Object);//true

console.log(true instanceof Boolean);//false
console.log(myBool instanceof Boolean);//true
console.log(myBool instanceof Object);//true

console.log(nullObj instanceof Object);//false

console.log(curDate instanceof Date);//true
console.log(curDate instanceof Object);//true
console.log(curDate instanceof String);//false

console.log('/^\d[.png]$/' instanceof RegExp);//false
console.log(myReg instanceof RegExp);//true
console.log(myReg instanceof Object);//true
  • 所以instanceof 也无法准确判定数据类型

3. Object.prototype.toString.call()

console.log(Object.prototype.toString.call(123));//[object Number]
console.log(Object.prototype.toString.call('123'));//[object String]
console.log(Object.prototype.toString.call(false));//[object Boolean]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(Symbol('Lawson')));//[object Symbol]
console.log(Object.prototype.toString.call(123n));//[object BigInt]

console.log(Object.prototype.toString.call(Array([5,2,5])));//[object Array]
console.log(Object.prototype.toString.call(new Date()));//[object Date]
console.log(Object.prototype.toString.call(new RegExp('^\d[.png]$')));//[object RegExp]
console.log(Object.prototype.toString.call(Object.create(null)));//[object Object]

console.log(Object.prototype.toString.call(new Set()));//[object Set]
console.log(Object.prototype.toString.call(new Map()));//[object Map]
  • 能准确判定出当前数据的类型

你可能感兴趣的:(【JS】数据类型判定)