在名为 weekTimes
的对象数组中,我正在寻找一个 date
属性等于 this.mon
的对象。如果找到对象,我希望其 hours
属性值填充称为 this.monTime
的 DOM input
元素。
然后我需要一周中的每一天都做同样的事情。我觉得一定有一种比我迄今为止所拥有的更优雅的方法来缩短所有这些(见下文),但我找不到。欢迎任何建议。
var temp;
temp = weekTimes.find(x => x.date === this.mon);
this.monTime = temp.hours;
temp = weekTimes.find(x => x.date === this.tue);
this.tueTime = temp.hours;
...
最佳答案
您可以使用属性(日期)名称数组来完成此操作:
["mon", "tue", "wed", "thu", "fri"].forEach(day => {
const temp = weekTimes.find(x => x.date === this[day]);
if (temp) this[day + "Time"] = temp.hours;
});
或者,您可以扭转局面,只需迭代 weekTimes
一次:
weekTimes.forEach(x => {
if (["mon","tue","wed","thu","fri"].includes(x.date)) {
this[x.date + "Time"] = x.hours;
}
});
如果确定 x.date
始终是感兴趣的一天,那么您甚至可以跳过 includes
测试:
weekTimes.forEach(x => this[x.date + "Time"] = x.hours);
输入元素?
您在问题中写道 this.monTime
指的是输入元素。但要设置输入元素的值,您需要设置其 value
属性。 monTime
是一个 setter 函数吗?如果没有,您可能应该使用额外的 .value
执行 this.monTime.value = ....
。
关于javascript - 是否有可能使用某种 ES6 语法将这两行合并为一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53574917/