如何在 JavaScript 中使用解構賦值交換變數?
解構賦值是ECMAScript 2015中引入的一個特性。該特性允許使用者提取陣列的內容和物件的屬性,而無需編寫重複的程式碼,從而將其拆分到不同的變數中
此賦值允許表示式將值從陣列和屬性解包到不同的變數中。
示例 1
在以下示例中,我們使用解構賦值來給變數賦值。在示例中,我們定義了兩個變數:first 和 second。在方法中,我們將解構變數以將陣列的變數分別賦值給 x 和 y。
# index.html
<!DOCTYPE html>
<html>
<head>
<title>Checking If a Number is Even</title>
</head>
<body>
<h1 style="color: green;">
Welcome To Tutorials Point
</h1>
<script>
let x;
let y;
let arr = ["First", "Second"];
[x, y] = arr;
console.log("x:", x);
console.log("y:", y);
</script>
</body>
</html>輸出

示例 2
在以下示例中,我們將賦值 first,如上例所示。一旦值被賦值,我們將交換這些值,然後將它們賦值給 x 和 y。
# index.html
<!DOCTYPE html>
<html>
<head>
<title>Checking If a Number is Even</title>
</head>
<body>
<h1 style="color: green;">
Welcome To Tutorials Point
</h1>
<script>
let x;
let y;
let arr = ["First", "Second", "Third", "Fourth", "Fifth"];
[x, y, ...rest] = arr;
[x, y] = [y,x];
console.log("x: ", x);
console.log("y: ", y);
console.log("Rest Numbers: ", rest);
</script>
</body>
</html>輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP