【问题标题】:What is the purpose of this array after the returned object?返回对象后这个数组的目的是什么?
【发布时间】:2019-10-29 13:52:55
【问题描述】:

有人能描述一下将 [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 将包含GBPUSD 并返回相应的元素。尚不清楚该函数为何采用currency 参数。
  • 谢谢。我认为文章提到货币参数是一个错误。我现在看到这只是括号表示法。我只是通常不会这样看。

标签: javascript arrays reactjs object ecmascript-6


【解决方案1】:

它所做的只是用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]);

【讨论】:

  • 拥有一个期望 [this.props.currency] 在范围内而不是简单地将其作为参数显式传递的函数是否存在潜在问题?这样写的唯一收获,是得到一个真正简洁的函数吗?或者还有更多的东西?这样做也意味着你的函数是不可重用的,而不是参数方法,你可以传递不同命名的变量。
  • React 不太好,但我相信this.props 是必需的。我会亲自使用传递的currency 参数来完成。
【解决方案2】:

货币是您要查找的对象部分的关键。

您可以将其重写为:

function getCurrencyData(currency) {
  const allAvailableData = {
    GBP: { base: 100, symbol: '£' },
    USD: { base: 100, symbol: '$' },
  }

  return allAvailableData[currency]
}

console.log(getCurrencyData('GBP'))
// { base: 100, symbol: '£' }
console.log(getCurrencyData('USD'))
// { base: 100, symbol: '$' }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-02
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    相关资源
    最近更新 更多