JS的相关数据类型概念
JS有八种数据类型,基本类型有7种,复杂数据类型1种
基本类型有: undefined,null,boolean,number,string,symbol,bigint
复杂数据类型:object 其中object类型中包含了Array,Date,Math,Function ,RegExp等
数据类型大致分成两类来进行存储
基础数据类型
基础数据类型存储在栈内存中,
被引用或拷贝时,会创建一个完全相等的变量
复杂数据类型
复杂数据类型存储在堆内存中,
存储的是地址,多个引用指向同一个地址,
这里会涉及一个“共享”的概念
const obj = {
name : 'tom',
age : 24
}
function change(o) {
o.age = 30
o = {
name: 'keke',
age : 18
}
return o
}
const objb = change(obj)
console.log(objb.age); // 18
console.log(obj.age); // 30
数据类型检测
typeof 检测
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefiend // 'undefiend'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object'
typeof [] // 'object'
typeof {} // 'object'
typeof console // 'object'
typeof console.log // 'function'
Instanceof 检测
//代码实现instanceof的原理
function myInstanceof(left, right) {
// 先用 typeof 检测是否为基本数据类型,若是,直接返回false
if (typeof left !== 'object' || left === null) return false
// getPrototypeOf 是 Object 对象自带的API 能够参数的原型对象
let proto = Object.getPrototypeOf(left)
while (true) {
if (proto === null) return false
if (proto === right.prototype) return true
proto = Object.getPrototypeOf(proto)
}
}
function Fun(name) {
this.name = name
}
const funObj = new Fun('Tom')
console.log(myInstanceof(funObj,Fun)); // true
两种判断数据类型的差异
- instanceof 可以准确判断复杂数据类型,但是不能正确判断基础数据类型
- typeof 虽可以判断基础数据(null除外),但是复杂数据类型中,除了
function类型除外,其他的也无法判断
Object.prototype.toString() 检测
console.log(Object.prototype.toString.call(11)) //[object Number]
console.log(Object.prototype.toString.call('123')) // [object String]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(null)) //[object Null]
console.log(Object.prototype.toString.call(function() {})) //[object Function]
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
数据类型转换
- Number()
- parseInt()
- parseFloat()
- toStirng()
- String()
- Boolean()
Number()转换
