javascript 類型判斷
js 内置类型:
基本类型:(存在栈中,做等号赋值操作进行的是值传递)
bigint, boolean, null, number, string, symbol, undefined
引用类型:(存在堆中,做等号赋值操作进行的是址传递)
Object:是 JS 中所有对象的父对象
Object包括:
Array, Boolean, Date, Math, Number, String, RegExp...
判断类型
1.typeof
let big = Bigint(1)
typeof big //"bigint"
let bool = true
typeof bool //"boolean"
typeof null //"object"
typeof 123 //"number"
typeof 'js' //"string"
let sym = Symbol('sym')
typeof sym // "symbol"
typeof undefined //"undefined"typeof 缺陷
暂时性死区(TDZ)
typeof x; // ReferenceError: x is not defined let x = '1'
判断 null 为 "object"
原因:
Javascript中二进制前三位都为0的话会被判断为Object类型,
null的二进制全为0,所以执行typeof为"object"
2.instanceof
//原理:只要右边变量的 prototype 在左边变量的原型链上即可
function _instanceof(left, right){
let l = left.__proto__;
let r = right.prototype;
if(l === r){
return true;
}else{
return false;
}
}
function Foo(){};
let foo = new Foo;
_instanceof(foo, Foo) //true
_instanceof([0], Array) //true
_instanceof(new Date, Date) //trueinstanceof 缺陷
[0] instanceof Object //true [0] instanceof Array //true //缺陷原因分析 [0].__proto__ === Array.prototype //true Array.prototype.__proto__ === Object.prototype //true Object.prototype.__proto__ === null//形成一条原型链,导致[0] instanceof Object 为 true
3.Object.prototype.toString
//1.基本类型
let big = Bigint(1)
Object.prototype.toString.call(big) //"[object BigInt]"
Object.prototype.toString.call(true) //"[object Boolean]"
Object.prototype.toString.call(null) //"[object Null]"
Object.prototype.toString.call(123) //"[object Number]"
Object.prototype.toString.call('js') //"[object String]"
Object.prototype.toString.call(Symbol()) //"[object Symbol]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
//2.引用类型
Object.prototype.toString.call({}) //"[object Object]"
Object.prototype.toString.call([]) //"[object Array]"
Object.prototype.toString.call(new Date) //"[object Date]"
Object.prototype.toString.call(function(){}) //"[object Function]"
Object.prototype.toString.call(/^/) //"[object RegExp]"
Object.prototype.toString.call(new Set) //"[object Set]"
Object.prototype.toString.call(new Map) //"[object Map]"2020.09.09更新:
结合typeof 与 Object.prototype.toString.call(),封装了toType函数,返回小写的数据类型名称。
{
let all2Type = {},
toString = all2Type.toString;
['Array', 'Bigint', 'Boolean', 'Date', 'Error', 'Function', 'Number', 'Object', 'RegExp', 'String', 'Symbol'].forEach(
name => {
all2Type[`[object ${name}]`] = name.toLowerCase();
}
);
const toType = function toType(obj){
if(obj === null) return obj + '';
return typeof obj === 'object' || typeof obj === 'function' ? all2Type[toString.call(obj)] || 'object' : typeof obj;
}
}點擊查看更多內容
2人點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦