js基本数据类型+判断数据类型方法

2021-10-26  本文已影响0人  林思念

数据类型分为基本类型和引用类型

基本类型:String、Number、Boolean、Null、Undefined、symbol(ES6)
引用类型:Object、Array、Date、Function、Error、RegExp、Math、Number、String、Boolean、Globle。
js内置类型七种:String、Number、Boolean、Null、Undefined、Symbol(ES6)、Object

判断数据类型的方法一般可以通过:typeof、instanceof、constructor、Object.prototype.toString.call();四种常用方法

1、typeof
typeof 1                                    // number 
typeof 'a'                                  // string
typeof true                                 // boolean
typeof undefined                            // undefined
typeof Symbol()                             // symbol
typeof 42n                                  // bigint
typeof function(){}                         // fucntion

注意:typeof null也是返回object,这是一个bug因为不同的对象在底层都是二进制存储,js中二进制前三位为0的话会被判断为object类型,而null的二进制都是0,造成误判。

2、instanceof(判断是否是某个类的实例

判断对象和构造函数在原型链上是否有关系,如果有关系,返回真,否则返回假

console.log(bool instanceof Boolean);        // false
console.log(num instanceof Number);          // false
console.log(str instanceof String);          // false
console.log(undefined instanceof Object);    // false
console.log(null instanceof Object);         // false
console.log(arr instanceof Array);           // true
console.log(obj instanceof Object);          // true
console.log(fun instanceof Function);        // true
console.log(s1 instanceof Symbol);           // false
3、constructor(查看对象对应的构造函数
console.log(bool.constructor === Boolean);   // true
console.log(num.constructor === Number);     // true
console.log(str.constructor === String);     // true
console.log(arr.constructor === Array);      // true
console.log(obj.constructor === Object);     // true
console.log(fun.constructor === Function);   // true
console.log(s1.constructor === Symbol);      // true
4、Object.prototype.toString(通用方法)
Object.prototype.toString.call(999)          // [object Number]
Object.prototype.toString.call('')           // [object String]
Object.prototype.toString.call(Symbol())     // [object Symbol]
Object.prototype.toString.call(42n)          // [object BigInt]
Object.prototype.toString.call(null)         // [object Null]
Object.prototype.toString.call(undefined)    // [object Undefined]
Object.prototype.toString.call(true)         // [object Boolean]
Object.prototype.toString.call({a:1})        // [object Object]
Object.prototype.toString.call([1,2])        // [object Array]
Object.prototype.toString.call(new Date)     // [object Date]
Object.prototype.toString.call(function(){}) // [object Function]

从这个结果也可以看出,不管是什么类型的,Object.prototype.toString.call();都可以判断出其具体的类型。
接下来我们分析一下四种方法各自的优缺点

image.png
上一篇下一篇

猜你喜欢

热点阅读