javascript 類型判斷

js 內置類型:git

基本類型:(存在中,作等號賦值操做進行的是值傳遞)github

bigint, boolean, null, number, string, symbol, undefinedurl

引用類型:(存在中,作等號賦值操做進行的是址傳遞)
es5

Object:是 JS 中全部對象的父對象spa

Object包括:.net

Array, Boolean, Date, Math, Number, String, RegExp...prototype

判斷類型code

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 缺陷ip

暫時性死區(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) //true

instanceof 缺陷

[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

ES5規範,利用引擎內部屬性 [[class]]

//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]"


點擊查看更多內容
相關文章
相關標籤/搜索