es6允許按照一定模式從陣列和物件中提取值,對變數進行賦值 稱為解構賦值
const aaa =
['張三'
,'李四'
,'王二'
,'麻子'];
let[zhang,li,wang,ma]
= aaa;
console.
log(zhang)
;//張三
console.
log(li)
;//李四
console.
log(wang)
//王二
console.
log(ma)
;//麻子
const arr =
["a"
,"b",[
"c",
"d",
["e"
,"f"
,"g"]]
];const[,
,[,,
[,, g]]]
= arr;
console.
log(g)
;// g
const arr1 =[1
,2,3
];const arr2 =
["a"
,"b"
,"c"];
const arr3 =
[...arr1,
...arr2]
;console.
log(arr3)
;// [1, 2, 3, "a", "b", "c"]
const arr4 =[1
,2,3
,4,5
,6];
const
[a, b,
...c]
= arr4;
console.
log(a)
;// 1
console.
log(b)
;// 2
console.
log(c)
;// 3, 4, 5, 6
只有當值是undefined的時候才會使用預設值,即使值是null也不會使用預設值
const arr =[1
, undefined, undefined,
null];
const
[a, b =
2, c, d =
"aaa"
]= arr;
console.
log(a)
;// 1
console.
log(b)
;// 2
console.
log(c)
;// undefined
console.
log(d)
;// null
交換變數不需要中間變數即可完成
let a =1;
let b =2;
[a,b]
=[b,a]
;console.
log(a)
;// 10
console.
log(b)
;// 20
const angula_info =
}let
= angula_info;
console.
log(name)
;//angula
console.
log(age)
;//18
console.
log(hanshu)
;//歡迎關注
hanshu()
//歡迎關注
// 可以使用:重新命名變數
const test =,,
]};const
= test;
const
= test;
const,]
}= test;
console.
log(skill_one)
;//
console.
log(skillname)
;// vue
console.
log(sklname_three)
;// jquery
const obj =
;const
= obj;
console.
log(
'name_one');
//js
console.
log(other)
;//
let age;
const obj =
//注意,下面這種寫法會報錯,這裡的大括號會認為是乙個塊級作用域
= obj;
//解決辦法
(= obj)
;//當然,為了引起不必要的麻煩,最好還是在宣告的同時進行解構賦值
let obj =
let;
console.
log(name)
;//angula
console.
log(age)
;//18
console.
log(skill)
;//["js","vue"]
// 字串的解構賦值
const str =
'my name is angula'
;const
[a,b,
...oth]
= str;
console.
log(a)
;//m
console.
log(b)
;//y
console.
log(oth)
;//[" ","n","a","m","e"," ","i","s"," ","a","n","g","u","l","a"]
//下面三行**是相同的,都輸出["m","y"," ","n","a","m","e"," ","i","s"," ","a","n","g","u","l","a"]
const
[...obj]
= str;
console.
log(obj)
const obj2 =
[...str]
; console.
log(obj2)
;const obj3 = str.
split(""
);console.
log(obj3)
ES6之 解構賦值
es6允許按照一定模式,從陣列和物件中提取值,對變數進行賦值,這被稱為解構賦值 destructuring 也可以簡稱 解構。下面用 進一步解釋一下什麼叫解構賦值。1.關於給變數賦值,傳統的變數賦值是這樣的 var arr 1,2,3 把陣列的值分別賦給下面的變數 var a arr 0 var b...
ES6之解構賦值
1.es6 允許按照一定模式,從陣列和物件中提取值,對變數進行賦值,這被稱為解構 let a,b,c 1,2 3 2.如果等號的右邊不是陣列 或者嚴格地說,不是可遍歷的結構,參見 iterator 一章 那麼將會報錯。如下例 let foo 1 let foo false let foo nan l...
ES6 之解構賦值
按照一定的模式,將陣列或物件中的資料提取出來,賦值給變數,這個過程叫做解構賦值 1 賦值 將陣列或物件中的資料提取出來,賦值給變數let arr 1 2,3 4,5 let 變數名 值 let a arr 0 let b arr 1 console.log a,b 2 解構 按照一定的模式 陣列模式...