0

正如你所看到的,我必须破坏我需要对它们求和并得到他们有多少收入的吸气剂。

这是一个示例代码,这是 Vuex 商店中的一个 getter,但这并不重要,它与 javascript 相关,而不是 vue 本身。

    sumIncomes: (
      {
        incomeMonthlyNet,
        incomePension,
        incomeChildBenefit,
        incomeChildSupports,
        incomeSpousalMaintenance,
        incomeParentalBenefit,
        incomeSecondaryWork,
        incomeSelfEmployedWork,
        incomeMiniJob,
        incomeSupplementaryPension,
        incomeRental,
      }
    ) => {
      return (
        incomeMonthlyNet +
        incomePension +
        incomeChildBenefit +
        incomeChildSupports +
        incomeSpousalMaintenance +
        incomeParentalBenefit +
        incomeSecondaryWork +
        incomeSelfEmployedWork +
        incomeMiniJob +
        incomeSupplementaryPension +
        incomeRental
      )
    },

这看起来一点也不优雅,但我突然找不到更好的方法(如果我可以将被破坏的对象存储在变量中,那么我可以使用 Object.values 并减少它,但我没有'不知道这样的)

谢谢你的帮助 ;)

4

1 回答 1

0

是的,你可以,这里有优雅的声明方式

sumIncomes: (
      incomeObject
    ) => {
      // If your object only contain income Properties you can do this
      return Object.values(incomeObject).reduce((acc, cur) => acc + cur,0)

      // If your object contain other keys and you know that income Properties all
      // have number values you can do this
      return Object.keys(incomeObject).reduce((acc, key) => key.startsWith('income') ? acc + incomeObject[key] : acc ,0)

      // if none of the above works because in your object you have a prop called for example incomeTest and 
      // its value is a string then you can do this
      const arrOfPropsToSum = ['incomeMonthlyNet',
        'incomePension',
        'incomeChildBenefit',
        'incomeChildSupports',
        'incomeSpousalMaintenance',
        'incomeParentalBenefit',
        'incomeSecondaryWork',
        'incomeSelfEmployedWork',
        'incomeMiniJob',
        'incomeSupplementaryPension',
        'incomeRental']
      return arrOfPropsToSum.reduce((acc, propKey) =>  acc + incomeObject[propKey], 0)
    },

这里有 3 个返回语句,显然除非您评论第一个,否则永远不会到达第二个和第三个。您可以通过评论第三个来尝试第二个,并通过评论第一个和第二个来尝试第三个。

于 2019-09-12T18:17:39.707 回答