1褒傅、數(shù)據(jù)類型:
- 數(shù)據(jù)類型分為:
-基本的數(shù)據(jù)類型(String, Number, boolean, Null, Undefined, Symbol)
特點(diǎn): 存儲(chǔ)的是該類型的真實(shí)值
-對(duì)象數(shù)據(jù)類型
特點(diǎn): 存儲(chǔ)的是該對(duì)象在堆內(nèi)存中的地址
2耳幢、克隆基本類型的數(shù)據(jù):
- 基本數(shù)據(jù)類型存放的就是實(shí)際的數(shù)據(jù)帮非,可直接克隆。
let number2 = 2;
let number1 = number2;
3褪秀、克隆對(duì)象數(shù)據(jù):
- 對(duì)象數(shù)據(jù)存放的是對(duì)象在堆內(nèi)存的地址,若直接克隆薛训,克隆的是地址媒吗。
let obj = {username: 'kobe'}
let obj1 = obj; //obj1
復(fù)制了obj在堆內(nèi)存的地址值,obj1和obj都指向一個(gè)對(duì)象
- 如何判斷是否克隆了對(duì)象類型:是否在堆里開(kāi)辟了新空間乙埃,創(chuàng)建了新的對(duì)象闸英。
- 分類: 淺克隆 與 深克隆。
2介袜、常用的拷貝(復(fù)制)技術(shù):
- `arr.concat()`: 數(shù)組淺拷貝
- `arr.slice()`: 數(shù)組淺拷貝
- `JSON.parse(JSON.stringify(arr/obj))`: 數(shù)組或?qū)ο笊羁截? 但不能處理函數(shù)數(shù)據(jù),使用場(chǎng)景是對(duì)象里不包含函數(shù)
- 淺拷貝包含函數(shù)數(shù)據(jù)的對(duì)象/數(shù)組
- 深拷貝包含函數(shù)數(shù)據(jù)的對(duì)象/數(shù)組
3甫何、擴(kuò)展:如何做到精準(zhǔn)判斷數(shù)據(jù)類型?
用:`Object.prototype.toString.call(xx)`遇伞,可以獲得類似 [object xx的類型名] 的字符串辙喂。
Object.prototype.toString.call(1) //[object Number]
Object.prototype.toString.call('1') //[object String]
Object.prototype.toString.call(undefined) //[object Undefined]
Object.prototype.toString.call(true)// [object Boolean]
Object.prototype.toString.call(console.log)//[object Function]
Object.prototype.toString.call(Symbol())//[object Symbol]
Object.prototype.toString.call([]) //[object Array]
Object.prototype.toString.call({}) //[object Object]
Object.prototype.toString.call(NaN)//[object Number]-------注意這里
相關(guān)代碼如下:
function getType(data) {
return Object.prototype.toString.call(data).slice(8,-1).toLowerCase()
}
//深度克隆
function deepClone(target) {
let result
if(getType(target) === 'array'){
result = []
}else if(getType(target) === 'object'){
result = {}
}else{
//如果傳入的不是數(shù)組,不是對(duì)象鸠珠,則直接返回巍耗,因?yàn)椴恍枰龠M(jìn)行深度克隆了。
return target
}
//循環(huán)遍歷出入的數(shù)組或者對(duì)象渐排,依次取出里面的內(nèi)容放入提前準(zhǔn)備好的容器(result)
for (let key in target){
let item = target[key]
if(getType(item) === 'array' || getType(item) === 'object'){
//拆到不能再拆
result[key] = deepClone(item)
}else{
result[key] = target[key]
}
}
return result
}
//驗(yàn)證數(shù)組
let arr = [1,2,3,4,5,{n:1,m:2,t:function(){console.log(1)}}]
let arr2 = deepClone(arr)
arr[0] = 9999999
arr[5].m = 100000000
console.log(arr2)
arr2[5].t()
//驗(yàn)證對(duì)象
let person = {
name:'kobe',
age:18,
sex:{opyion1:'男',option2:'女'},
speak(){
console.log('我說(shuō)話了')
}
}