React ES6 解构
解构
为了演示解构,我们将制作一个三明治。你会把冰箱里的东西都拿出来做三明治吗?不,你只拿你想在三明治上用的东西。
解构是完全相同的。我们可能有一个正在使用的数组或对象,但我们只需要其中包含的一些项。
解构使得只提取所需内容变得容易。
解构数组
下面是将数组项分配给变量的旧方法:
之前:
const vehicles = ['mustang', 'f-150', 'expedition'];
// old way
const car = vehicles[0];
const truck = vehicles[1];
const suv = vehicles[2];
Here is the new way of assigning array items to a variable:
使用解构:
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car, truck, suv] = vehicles;
在分解数组时,变量的声明顺序很重要。
如果我们只想要汽车和 suv,我们可以省去卡车,但保留逗号:
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car,, suv] = vehicles;
当函数返回一个数组时,解构就很方便了:
实例
<!DOCTYPE html>
<html>
<body>
<script>
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);
document.write("<p>Sum: " + add + "</p>");
document.write("<p>Difference " + subtract + "</p>");
document.write("<p>Product: " + multiply + "</p>");
document.write("<p>Quotient " + divide + "</p>");
</script>
</body>
</html>
解构 对象
下面是在函数中使用对象的旧方法:
之前:
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 + '.';
}
下面是在函数中使用对象的新方法:
使用解构:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
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 + '.';
document.getElementById("demo").innerHTML = message;
}
</script>
</body>
</html>
请注意,对象属性不必按特定顺序声明。
我们甚至可以通过引用嵌套对象,然后使用冒号和大括号再次分解嵌套对象中所需的项,来分解深度嵌套对象:
实例
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
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 + '.';
document.getElementById("demo").innerHTML = message;
}
</script>
</body>
</html>