数组的解构赋值
1,简单的例子
const arr = [1, 2, 3, 4];
let [a, b, c, d] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); // 4
2,更复杂的匹配规则
const arr = ["a", "b", ["c", "d", ["e", "f", "g"]]];
const [, , [, , [, , g]]] = arr;
console.log(g); // g
3,扩展运算符...
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
4,默认值
// 只有当值是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
5,交换变量
// 不需要中间变量
let a = 20;
let b = 10;
[a, b] = [b, a];
console.log(a); // 10
console.log(b); // 20
对象的解构赋值
1,一般的例子
// 使用对象的结构赋值是,属性名必须跟解构对象的属性名一致
// 因为对象与数组不同,对象是无序的,只能通过属性名来标识
const xiaoming = {
name: "小明",
age: 10
};
const { name, age } = xiaoming;
console.log(name); // 小明
console.log(age); // 10
2,更复杂的结构条件
// 可以使用:重命名变量
const player = {
nickname: "感情的戏我没演技",
master: "东海龙王",
skill: [
{
skillName: "龙吟",
mp: "100",
time: 6000
},
{
skillName: "龙卷雨击",
mp: "400",
time: 3000
},
{
skillName: "龙腾",
mp: "900",
time: 60000
}
]
};
const { nickname } = player;
const { master } = player;
const {
skill: [skill1, { skillName }, { skillName: sklName }]
} = player;
console.log(skill1); // {skillName: "龙吟", mp: "100", time: 6000}
console.log(skillName); // 龙卷雨击
console.log(sklName); // 龙腾
3,结合扩展运算符
const obj = {
saber: "阿尔托利亚",
archer: "卫宫",
lancer: "瑟坦达"
};
const { saber, ...oth } = obj;
console.log(saber); // 阿尔托利亚
console.log(oth); // {archer: "卫宫", lancer: "瑟坦达"}
4,如何对已经申明了的变量进行对象的解构赋值
let age;
const obj = {
name:'小明',
age:22
};
{ age } = obj; // 这样是会报错的,因为这里的{}被认为是一个块级作用域
({ age } = obj); // <= 解决办法
// 不过,最好还是在声明的同时进行解构赋值
5,默认值
// 默认值
let girlfriend = {
name: "小红"
};
let { name, age = 24, hobby = ["学习"] } = girlfriend;
console.log(name); // 小红
console.log(age); // 24
console.log(hobby); // ["学习"]
字符串的解构赋值
const str = "I am the bone of my sword"; // 我是剑骨头
const [a, b, c, ...oth] = str;
console.log(a); // "I"
console.log(b); // " "
console.log(c); // "a"
console.log(oth); // ["m", " ", "t", "h", "e", " ", "b", "o", "n", "e", " ",
// "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]
// 以下三个的结果是一样的
const [...spStr1] = str;
const spStr2 = str.split("");
const spStr3 = [...str];
console.log(spStr1); // ["I", " ", "a", "m", " ", "t", "h", "e", " ", "b", "o", "n",
// "e", " ", "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]
console.log(spStr2); // ["I", " ", "a", "m", " ", "t", "h", "e", " ", "b", "o", "n",
// "e", " ", "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]
console.log(spStr3); // ["I", " ", "a", "m", " ", "t", "h", "e", " ", "b", "o", "n",
// "e", " ", "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]
网友评论