Object destructuring,用于提取对象属性
const product ={
label: "Note book",
price: 23,
stock: 100
};
const {stock, label, price} = product;
console.log(label, price, stock); // Note book 23 100
可以改名称,也可以提取不存在的属性,值为undefined.
const {stock, label : newLabelName, price, rating } = product;
console.log(newLabelName, price, stock, rating); // Note book 23, 100, undefined.
如下的code:
const transaction = ({ label, stock }) => {
console.log(label, stock);
};
const product = { label: "handy", stock: 100 };
transaction(product); // Ok
transaction(); // Cannot destructure property 'label' of 'undefined' as it is undefined.
如果transaction
在调用时,没有提供参数,程序会crash,为了解决此issue, transaction
函数提供默认参数,一个空的对象:
const transaction = ({ label, stock } = { }) => {
console.log(label, stock);
};
transaction(); // undefined, undefined