【ECMAScript 5_6_7】3、ES6——變數的解構賦值
阿新 • • 發佈:2019-01-09
一、變數的解構賦值
1. 理解: * 從物件或陣列中提取資料, 並賦值給變數(多個) 2. 物件的解構賦值 let {n, a} = {n:'tom', a:12} 3. 陣列的解構賦值 let [a,b] = [1, 'onedean']; 4. 用途 * 給多個形參賦值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>03_變數的解構賦值</title> </head> <body> <script type="text/javascript"> let obj = { username:'onedean', age:20 } /*let username = obj.username let age = obj.age*/ let {username,age} = obj console.log(username,age) // onedean 20 let arr = [1,3,5,'abc',true] let [a,b,c,d,e] = arr console.log(a,b,c,d,e) // 1 3 5 "abc" true let [,,xxx] = arr console.log(xxx) // 5 function person(obj) { // 不用解構賦值 console.log(obj.username,obj.age) // onedean 20 } person(obj) function person1({username,age}) { // onedean 20 使用解構賦值,此處相當於{username,age} = obj console.log(username,age) } person1(obj) </script> </body> </html>