详解 -- 解构赋值

99 阅读1分钟

对象解构赋值

const obj = {
    name: '苏苏',
    age: 18,
    height: 1.85,
    testObjectDeep: {
        test: 'ObjectDeep'
    },
    testArrayDeep: ['anna', 'emma', 'duo', ['son']]
};
// 1.解构后重命名 2.正常解构 3.赋默认值 4.重命名+赋默认值(address: newAddress = '不存在')
const { name: newName, age, address = '不存在' } = obj;
console.log(newName, age, address);
// 深层解构(但要注意的是每解构一层上一层就不能用了)
const {
    testObjectDeep: { test },
    // 需要注意的是数组内部的数组就不能再进行解构了
    testArrayDeep: [name1, , name3, son]
} = obj;

console.log(test, name1, name3, son);

// 细节点
const obj = {
  name: '苏苏',
  age: 18
}

let name = 'age';
// 通过name变量去找obj中对应的key拿到后重命名供后续使用
const { [name]: variable } = obj;
console.log(variable);

数组解构赋值

const names = ['苏苏', '土狗', 'SharkDog'];
// 数组根据下标结构复制(想跳过某个值就用逗号)
const [, susu] = names; // 等于 const susu = names[1];
// 等于 const arr = names.slice(1)
const [name, ...arr] = names;
// 等于 const overflow = names[3] === void 0 ? '越界了' : names[3];
// 以上又等于 const overflow = names[3] === undefined ? '越界了' : names[3];
const [, , , overflow = '越界了'] = names;
// 相当于 const susu = names[1]
console.log(susu);
console.log(arr);
console.log(overflow);

console.log(names);