注意点
对象的解构赋值和数组的解构赋值,除了符号不一样,其它的一模一样。数组解构使用 []
,对象解构使用 {}
,在数组的解构赋值中,等号左边的格式必须和等号右边的格式一模一样,才能完全解构,例如如下代码:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let [a, b, c] = [1, 3, 5];
console.log(a, b, c);
</script>
</head>
<body>
</body>
</html>
在数组的解构赋值中,两边的个数可以不一样:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let [a, b] = [1, 3, 5];
console.log(a, b);
let [c, d, e] = [1, 3];
console.log(c, d, e);
</script>
</head>
<body>
</body>
</html>
在数组的解构赋值中,如果右边少于左边,我们可以给左边指定默认值:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let [a, b, c = 666] = [1, 3];
console.log(a, b, c);
</script>
</head>
<body>
</body>
</html>
如上都是数组的解构赋值,接下来就来看看对象的解构赋值:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let obj = {
name: "BNTang",
age: 34
}
let name = obj.name;
let age = obj.age;
console.log(name, age);
</script>
</head>
<body>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let obj = {
name: "BNTang",
age: 34
}
let {name, age} = obj;
console.log(name, age);
</script>
</head>
<body>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let {name, age} = {name: "BNTang", age: 34};
console.log(name, age);
</script>
</head>
<body>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let {name} = {name: "BNTang", age: 34};
console.log(name);
</script>
</head>
<body>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let {name, age, height} = {name: "BNTang", age: 34};
console.log(name, age, height);
</script>
</head>
<body>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let {name, age, height = 1.80} = {name: "BNTang", age: 34};
console.log(name, age, height);
</script>
</head>
<body>
</body>
</html>
注意点:在对象解构赋值中,左边的变量名称必须和对象的属性名称一致,才能解构出数据:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let {a, b} = {name: "BNTang", age: 34};
console.log(a, b);
</script>
</head>
<body>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let {age} = {name: "BNTang", age: 34};
console.log(age);
</script>
</head>
<body>
</body>
</html>