结构赋值
1、数组
var arr = [1, 2, 3]
var arr2 = ['lmj', 'lhc', 'pfc']
const [a, c, b] = arr
console.log(a, b, c);
const [d, e, f] = arr2
console.log(d, e, f);
const [ , , g] = arr2
console.log(g);
2、对象
var obj = {
name: 'lmj',
age: 21,
doing: {
good: 'good!',
bad: 'bad'
}
}
var arr = ['name', 'age']
const {[arr[0]]: pername, [arr[1]]: perage} = obj
console.log(pername, perage);
const {name, age: myage, doing: {good: test}} = obj
console.log(name, myage, test);
const {name: name2, age: age2 = '99', gender: gender = '男'} = obj
console.log(name2, age2, gender);
const {name: name3, age: age3, ...perObj} = obj
console.log(perObj);
let gender = '女';
({gender} = obj);
console.log(gender);
3、函数,字符串,Map
function getAPI(data){
return [data.name, data.age]
}
const [lmjname, lmjage] = getAPI({name: 'lmj', age: 21})
console.log(lmjname, lmjage)
var str = '刘明杰今天学习了吗?'
const [first, second, third, ...last] = str
console.log(first, second, third, last);
const namelist = ['刘明杰', '彭富春', '陆浩城', '沈洋', '韩世凯']
namelist.forEach(([item], index) => {
console.log(item);
})
let map = new Map();
map.set('name1', '刘明杰')
map.set('name2', '彭富春')
map.set('name3', '陆浩城')
for (let [,value] of map){
console.log(value);
}