解構賦值是 ES6 中引入的一種語法糖,它允許您將數組或物件中的值解構到變數中。它可以顯著簡化您的程式碼並使其更具可讀性。
基本範例:
const numbers = [1, 2, 3, 4]; const [first, second, ...rest] = numbers; console.log(first); // Output: 1 console.log(second); // Output: 2 console.log(rest); // Output: [3, 4]
const [first, , third] = numbers; console.log(first, third); // Output: 1 3
const nestedArray = [[1, 2], [3, 4]]; const [[a, b], [c, d]] = nestedArray; console.log(a, b, c, d); // Output: 1 2 3 4
基本範例:
const person = { name: 'Alice', age: 30, city: 'New York' }; const { name, age, city } = person; console.log(name, age, city); // Output: Alice 30 New York
const { name: firstName, age, city } = person; console.log(firstName, age, city); // Output: Alice 30 New York
const { name, age = 25, city } = person; console.log(name, age, city); // Output: Alice 30 New York
const person = { name: 'Alice', address: { street: '123 Main St', city: 'New York' } }; const { name, address: { street, city } } = person; console.log(name, street, city); // Output: Alice 123 Main St New York
解構可以用來簡潔地交換變數:
let a = 10; let b = 20; [a, b] = [b, a]; console.log(a, b); // Output: 20 10
您可以解構函數參數以使其更具可讀性:
function greet({ name, age }) { console.log(`Hello, ${name}! You are ${age} years old.`); } greet({ name: 'Alice', age: 30 });
透過有效地使用解構賦值,您可以編寫更乾淨、更簡潔、更易讀的 JavaScript 程式碼。
以上是JavaScript 中解構賦值的強大範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!