谁能描述一下 [this.props.currency] 放在返回对象之后的目的,或者我可以阅读有关此模式的地方,因为我以前从未见过它。
我不是在问 this.props.currency 是什么,而是它在返回对象之后的用途。
在这篇博文中看到: https://javascriptplayground.com/react-extracting-logic/
export const getCurrencyData = currency => {
return {
GBP: { base: 100, symbol: '£' },
USD: { base: 100, symbol: '$' },
}[this.props.currency];
};
最佳答案
它所做的只是使用 this.props.currency
的键获取属性的值 - 所以如果 currency
是 "GBP"
,返回值为{ base: 100, symbol: "£"}
。你可以这样写,这样更清楚:
export const getCurrencyData = currency => {
const obj = {
GBP: { base: 100, symbol: '£' },
USD: { base: 100, symbol: '$' }
};
return obj[this.props.currency];
};
您还可以利用带有箭头函数的显式返回功能来删除 return
关键字:
export const getCurrencyData = currency => ({
GBP: { base: 100, symbol: '£' },
USD: { base: 100, symbol: '$' },
}[this.props.currency]);
关于javascript - 返回对象后这个数组的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56606425/