前端数据类型
基础数据类型:string,number,boolean,null,undefined,symbol,bigint(后两个为ES6新增)
引用数据类型:object(普通对象,数组对象,正则对象,日期对象,Math数学函数对象),function
基础数据类型与引用数据类型的区别:
1.基础数据类型存储在栈,引用数据类型存储在堆。
2.堆比栈空间大,栈比堆运行速度快。
3.堆内存是无序存储,可以根据引用直接获取。
4.基础数据类型比较稳定,而且相对来说占用的内存小。
5.引用数据类型大小是动态的,而且是无限的。
数据类型的判断
typeof
能判 number,string,boolean,undefined,symbol,object和function类型
console.log(typeof 1); //number
console.log(typeof '1'); //string
console.log(typeof true); //boolean
console.log(typeof undefined); //undefined
console.log(typeof null); //object
console.log(typeof []); //object
console.log(typeof {}); //object
instanceOf
instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。instanceOf 主要用于复合类型的判断,对于基础的数据类型不适用。
console.log(1 instanceof Number); //false
console.log('1' instanceof String); //false
console.log(true instanceof Boolean); //false
console.log([] instanceof Array); //true
console.log([] instanceof Object); //true
console.log({} instanceof Object); //true
左侧必须是 object 类型
let num = new Number(1)
num instanceof Number // true
instanceOf 实现
function new_instance_of(leftVaule, rightVaule) {
let rightProto = rightVaule.prototype; // 取右表达式的 prototype 值
leftVaule = leftVaule.__proto__; // 取左表达式的__proto__值
while (true) {
if (leftVaule === null) {
return false;
}
if (leftVaule === rightProto) {
return true;
}
leftVaule = leftVaule.__proto__
}
}
constructor
null 和 undefined 没有 constructor
函数的 constructor 是不稳定的,这个主要体现在自定义对象上,当开发者重写 prototype 后,原有的 constructor 引用会丢失,constructor 会默认为 Object
let a = 1
console.log(a.constructor === Number); //true
console.log('1'.constructor === String); //true
console.log(true.constructor === Boolean); //true
console.log([].constructor === Array); //true
toString
toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型。
对于 Object 对象,直接调用 toString() 就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息。
Object.prototype.toString.call('') ; // [object String]
Object.prototype.toString.call(1) ; // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]