JavaScript解构赋值是一种简化变量赋值的语法,允许从数组或对象中提取数据并将其赋值给变量。【https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment】
1.数组解构赋值
- let numbers = [1, 2, 3];
- let [a, b, c] = numbers;
- console.log(b); // 输出: 2
- console.log(a, b, c); // 输出: 1 2 3
2.对象解构赋值
- let person = {
- name: 'Alice',
- age: 25,
- gender: 'female'
- };
- let { name, age, gender } = person;
- console.log(name, age, gender); // 输出: Alice 25 female
3.解构赋值时还可以给变量设置默认值,可以通过指定默认值来处理不存在的变量
- let arr = [1, 2];
- let [x, y, z = 3] = arr;
- console.log(x, y, z); // 输出: 1 2 3
4.JavaScript的解构赋值不仅可以用于简单的数组和对象,还可以用于嵌套的结构、函数参数和返回值的解构。
☆ 嵌套结构的解构赋值:
- let nestedObj = {
- outer: {
- inner: {
- value: 42
- }
- }
- };
- let { outer: { inner: { value } } } = nestedObj;
- console.log(value); // 输出 42
☆ 函数参数的解构赋值:
- 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."
☆ 函数返回值的解构赋值:
- function getFullName({ firstName, lastName }) {
- return {
- fullName: `${firstName} ${lastName}`
- };
- }
- const { fullName } = getFullName({ firstName: "John", lastName: "Doe" });
- console.log(fullName); // 输出 "John Doe"