如何优化这段返回结构化数组的Vue计算属性JS代码?
优化方案
可以通过提取公共重复项的方式简化代码,既减少冗余,也提升后续的可维护性——毕竟如果profile相关的字段需要修改,只需要改一处即可。
写法一:提取公共项 + 三元表达式
// 抽离重复的profile条目 const profileEntry = { label: this.$t('profile'), value: this.acc.AccountNumber, id: 'ProfileNumber' }; return this.isThis ? [ { label: this.$t('market'), value: this.acc.label, id: 'market' }, profileEntry, { label: this.$t('account'), value: this.acc.profile, id: 'account' } ] : [profileEntry];
写法二:扩展运算符简化数组拼接
如果偏好更紧凑的逻辑,也可以用扩展运算符直接合并基础数组与条件项:
const baseEntries = [{ label: this.$t('profile'), value: this.acc.AccountNumber, id: 'ProfileNumber' }]; return this.isThis ? [ { label: this.$t('market'), value: this.acc.label, id: 'market' }, ...baseEntries, { label: this.$t('account'), value: this.acc.profile, id: 'account' } ] : baseEntries;
为什么这样更优?
- 消除了重复的对象字面量,避免后续修改时出现漏改的情况
- 逻辑分支更清晰,一眼就能看出两种场景下的差异项
- 代码结构更简洁,可读性更强
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

