【发布时间】:2020-06-10 10:16:07
【问题描述】:
我有 3 个对象
var first = {name:'ab', age:'12',year:'2010',color:'red'};
var second = {name:'ax', age:'14',year:'2011',mood:'sour'};
var third = {name:'ay', age:'15',year:'2012',dessert:'cake'};
我需要访问第一个、第二个和第三个中的项目,我目前通过解构来完成。
let {name, age, year, color} = a;
//perform some action here
let {name, age, year, mood} = b;
//perform some action here
let {name, age, year, dessert} = c;
//perform some action here.
注意:例如。我只在每个对象中显示几个项目,在现实世界的情况下,我有大约 20 多个,其中 15 个在所有对象中重复出现。
由于我每次都重复姓名、年龄和年份,有没有办法优化我可以在其他地方声明这 3 个变量并在解构时提及的代码。
例如:
let commonVars = {name, age, year}
let {...commonvars, color} = a;
let {...commonvars, mood} = b;
let {...commonvars, dessert} = c;
因为我似乎一遍又一遍地重复这一点。
【问题讨论】:
-
为什么不使用函数呢?
({name, age, year}) => { /* whatever */} -
不,没有。无论如何,您不能重新使用相同的名称。
-
为什么不能使用点表示法而不是创建新变量?
first.name,second.name。连这个first/fifteenth好像都用错了 -
为什么不使用数组?
-
@VLAZ,这些是多个对象,其中大约 15 个变量重复,而其余变量是唯一的。所以我也不能假设。让我更新问题
标签: javascript object javascript-objects destructuring