寫vue或react項目,我們經常在接收到數據的時候,需要對數據進行二次加工操作,一些傳統的辦法可以實現對數據的加工。但利用到ES6的解構賦值,則更為簡單。
解構賦值主要分為對象的解構和數組的解構,在沒有解構賦值的時候,我們的賦值是這樣的
let arr = [1,2,3]
let a= arr[0]
let b= arr[1]
let c= arr[2]
這樣寫很繁瑣,解構賦值可以輕松解決上面的問題。
一、數組的解構賦值
let arr = [0,1,2]
let [a,b,c]=arr
console.log(a)//0
console.log(b) //1
console.log(c) //2
但是很多時候,數據並非一一對應的,並且我們希望得到一個默認值
let arr = [,1,2]
let [a='我是默認值',b,c] =arr
console.log(a)//'我是默認值'
console.log(b) //1
console.log(c) //2
從這個例子可以看出,在解構賦值的過程中,a=undefined時,會使用默認值
那么當a=null時呢?當a=null時,那么a就不會使用默認值,而是使用null
//數組的拼接
let a = [0,1,2]
let b= [3,4,5]
let c=a.concat(b)
console.log(c)//[0,1,2,3,4,5]
let d=[...a,...b]
console.log(d)//[0,1,2,3,4,5]
//數組的克隆//假如我們簡單地把一個數組賦值給另外一個變量
let a = [0,1,2,3]
let b=a
b.push(4)
console.log(a)//[0,1,2,3,4]
console.log(b) //[0,1,2,3,4]
因為這只是簡單的把引用地址賦值給b,而不是重新開辟一個內存地址,所以a和b共享了同一個內存地址,該內存地址的更改,會影響到所有引用該地址的變量,那么用下面的方法,把數組進行克隆一份,互不影響。
let a = [0,1,2,3]
let b=[...a]
b.push(4)
console.log(a)//[0,1,2,3]
console.log(b) //[0,1,2,3,4]
二、對象的解構賦值
對象的解構賦值和數組的解構賦值其實類似,但是數組的數組成員是有序的
而對象的屬性則是無序的,所以對象的解構賦值簡單理解就是等號的左邊和右邊的解構相同
let {name,age} = {name:"swr",age:28}
console.log(name)//'swr'
console.log(age) //28
對象的解構賦值是根據key值進行匹配
let { name:Name,age } = { name:'swr',age:28}
console.log(Name)//'swr'
console.log(age) //28