Introduction to JavaScript destructuring assignment
JavaScript destructuring assignment is a syntax that simplifies variable assignment, allowing data to be extracted from an array or object and assigned to a variable. 【https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment】
1. Array destructuring and assignment
let numbers = [1, 2, 3];
let [a, b, c] = numbers;
console.log(b); // 输出: 2
console.log(a, b, c); // 输出: 1 2 3
2. Object destructuring and assignment
let person = {
name: 'Alice',
age: 25,
gender: 'female'
};
let { name, age, gender } = person;
console.log(name, age, gender); // 输出: Alice 25 female
3. When destructuring and assigning values, you can also set default values for variables. You can deal with non-existent variables by specifying default values.
let arr = [1, 2];
let [x, y, z = 3] = arr;
console.log(x, y, z); // 输出: 1 2 3
4. JavaScript’s destructuring assignment can be used not only for simple arrays and objects, but also for destructuring nested structures, function parameters, and return values.
☆ Destructuring assignment of nested structures:
let nestedObj = {
outer: {
inner: {
value: 42
}
}
};
let { outer: { inner: { value } } } = nestedObj;
console.log(value); // 输出 42
☆ Destructuring assignment of function parameters:
function greet({ name, age }) {
console.log(`Hello, my name is ${name} and I am ${age} years old.`);
}
greet({ name: "Alice", age: 30 }); // 输出 "Hello, my name is Alice and I am 30 years old."
☆ Destructuring assignment of function return value:
function getFullName({ firstName, lastName }) {
return {
fullName: `${firstName} ${lastName}`
};
}
const { fullName } = getFullName({ firstName: "John", lastName: "Doe" });
console.log(fullName); // 输出 "John Doe"