什么是數組的解構賦值
解構賦值是 ES6
中新增的一種賦值方式。
數組解構賦值的注意點
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
let arr = [1, 3, 5];
let a = arr[0];
let b = arr[1];
let c = arr[2];
console.log("a = " + a);
console.log("b = " + b);
console.log("c = " + c);
console.log("********************");
let [d, e, f] = arr;
console.log("d = " + d);
console.log("e = " + e);
console.log("f = " + f);
</script>
</head>
<body>
</body>
</html>
在數組的解構賦值中, 等號左邊的格式必須和等號右邊的格式一模一樣, 才能完全解構。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
let [a, b, c] = [1, 3, 5];
let [d, e, f] = [1, 3, [2, 4]];
let [g, h, [i, j]] = [1, 3, [2, 4]];
console.log("a = " + a);
console.log("b = " + b);
console.log("c = " + c);
console.log("d = " + d);
console.log("e = " + e);
console.log("f = " + f);
console.log("g = " + g);
console.log("h = " + h);
console.log("i = " + i);
console.log("j = " + j);
</script>
</head>
<body>
</body>
</html>
在數組的解構賦值中, 左邊的個數可以和右邊的個數不一樣。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
let [a, b] = [1, 3, 5];
console.log("a = " + a);
console.log("b = " + b);
</script>
</head>
<body>
</body>
</html>
在數組的解構賦值中, 右邊的個數可以和左邊的個數不一樣。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
let [a, b, c] = [1];
console.log("a = " + a);
console.log("b = " + b);
console.log("c = " + c);
</script>
</head>
<body>
</body>
</html>
在數組的解構賦值中, 如果右邊的個數和左邊的個數不一樣, 那么我們可以給左邊指定默認值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
let [a, b = 666, c = 888] = [1];
console.log("a = " + a);
console.log("b = " + b);
console.log("c = " + c);
</script>
</head>
<body>
</body>
</html>
在數組的解構賦值中, 如果左邊的個數和右邊的個數不一樣, 那么如果設置默認值會被覆蓋。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
let [a, b = 666] = [1, 3, 5];
console.log("a = " + a);
console.log("b = " + b);
</script>
</head>
<body>
</body>
</html>
- 在數組的解構賦值中, 還可以使用 ES6 中新增的擴展運算符來打包剩余的數據。
- 在數組的解構賦值中, 如果使用了擴展運算符, 那么擴展運算符只能寫在最后。
- ES6 中新增的
擴展運算符
:...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
let [a, b] = [1, 3, 5];
let [c, ...d] = [1, 3, 5];
let [e, ...f] = [1, 3, 5];
console.log("a = " + a);
console.log("b = " + b);
console.log("c = " + c);
console.log("d = " + d);
console.log("e = " + e);
console.log("f = " + f);
</script>
</head>
<body>
</body>
</html>