js 内置类型:
基本类型:(存在栈中,做等号赋值操作进行的是值传递)
bigint, boolean, null, number, string, symbol, undefined
引用类型:(存在堆中,做等号赋值操作进行的是址传递)
Object:是 JS 中所有对象的父对象
Object包括:
Array, Boolean, Date, Math, Number, String, RegExp…
判断类型
1.typeof
1 2 3 4 5 6 7 8 9 10 | 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)
1 2 | typeof x; // ReferenceError: x is not defined let x = '1' |
判断 null 为 “object”
原因:
Javascript中二进制前三位都为0的话会被判断为Object类型,
null的二进制全为0,所以执行typeof为”object”
2.instanceof
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //原理:只要右边变量的 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 缺陷
1 2 3 4 5 6 | [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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //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]" |
本文来自投稿,不代表程序员编程网立场,如若转载,请注明出处:http://www.cxybcw.com/202177.html