Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

React ES6 结构赋值


结构赋值

为了说明结构赋值,我们将做一个三明治。你会把冰箱里的所有东西都拿出来做三明治吗?不会,你只会拿出你想在三明治上使用的物品。

结构赋值完全一样。我们可能正在使用一个数组或对象,但我们只需要其中的一些项目。

结构赋值可以轻松提取所需内容。


解构数组

这是将数组项分配给变量的旧方法

示例

之前

const vehicles = ['mustang', 'f-150', 'expedition'];

// old way
const car = vehicles[0];
const truck = vehicles[1];
const suv = vehicles[2];

这是将数组项分配给变量的新方法

示例

使用结构赋值

const vehicles = ['mustang', 'f-150', 'expedition'];

const [car, truck, suv] = vehicles;

在解构数组时,声明变量的顺序很重要。

如果我们只想得到 car 和 suv,我们可以简单地省略 truck,但保留逗号

const vehicles = ['mustang', 'f-150', 'expedition'];

const [car,, suv] = vehicles;

当函数返回一个数组时,结构赋值会派上用场

示例

function calculate(a, b) {
  const add = a + b;
  const subtract = a - b;
  const multiply = a * b;
  const divide = a / b;

  return [add, subtract, multiply, divide];
}

const [add, subtract, multiply, divide] = calculate(4, 7);

自己试试 »


w3schools CERTIFIED . 2022

获得认证!

完成 React 模块,进行练习,参加考试,并获得 w3schools 认证!!

$95 报名

解构对象

这是在函数内部使用对象的旧方法

示例

之前

const vehicleOne = {
  brand: 'Ford',
  model: 'Mustang',
  type: 'car',
  year: 2021, 
  color: 'red'
}

myVehicle(vehicleOne);

// old way
function myVehicle(vehicle) {
  const message = 'My ' + vehicle.type + ' is a ' + vehicle.color + ' ' + vehicle.brand + ' ' + vehicle.model + '.';
}

这是在函数内部使用对象的新方法

示例

使用结构赋值

const vehicleOne = {
  brand: 'Ford',
  model: 'Mustang',
  type: 'car',
  year: 2021, 
  color: 'red'
}

myVehicle(vehicleOne);

function myVehicle({type, color, brand, model}) {
  const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';
}

自己试试 »

请注意,对象属性不必以特定顺序声明。

我们甚至可以通过引用嵌套对象,然后使用冒号和花括号再次解构从嵌套对象中需要的项目,来解构深度嵌套的对象

示例

const vehicleOne = {
  brand: 'Ford',
  model: 'Mustang',
  type: 'car',
  year: 2021, 
  color: 'red',
  registration: {
    city: 'Houston',
    state: 'Texas',
    country: 'USA'
  }
}

myVehicle(vehicleOne)

function myVehicle({ model, registration: { state } }) {
  const message = 'My ' + model + ' is registered in ' + state + '.';
}

自己试试 »



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.