在名为pane {
-fx-background-color: rgba(255,0,0,0.5);
}
的对象数组中,我正在寻找一个weekTimes
属性等于date
的对象。如果找到了对象,我希望它的this.mon
属性值填写一个称为hours
的DOM input
元素。
然后,我需要在一周的每一天做同样的事情。我觉得必须有比目前为止(见下文)更精巧的方法来缩短所有这些时间,但是我找不到。任何建议都将受到欢迎。
this.monTime
答案 0 :(得分:6)
您可以使用一组属性(日期)名称来完成此操作:
["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函数吗?如果没有,您可能应该用额外的this.monTime.value = ....
来.value
。
答案 1 :(得分:0)
您还可以考虑使用一种更具功能性的方法,并避免依赖外部范围来执行更新:(我从您的示例中假设是这种情况)
这是一个获取日期以在时间对象列表中查找的函数。如果找到对象,它将执行给定的回调:
/**
* Finds in given list of times, a time which date property is set to given date.
* When a time is found, pass it as an argument to given callback.
* When no time is found, callback is not executed
* @param date {string}
* @param times {time[]}
* @param cb {function}
*/
const whenCurrentDay = (date, times, cb) => {
const found = times.find(time => time.date === date);
found && cb(found);
};
然后您将按以下方式使用它:
whenCurrentDay('mon', weekTimes, time => console.log(`do something with ${time.hours}`));
whenCurrentDay('tue', weekTimes, time => console.log(`do something with ${time.hours}`));
whenCurrentDay('wed', weekTimes, time => console.log(`do something with ${time.hours}`));
whenCurrentDay('thu', weekTimes, time => console.log(`do something with ${time.hours}`));
whenCurrentDay('fri', weekTimes, time => console.log(`do something with ${time.hours}`));
whenCurrentDay('sat', weekTimes, time => console.log(`do something with ${time.hours}`));
whenCurrentDay('sun', weekTimes, time => console.log(`do something with ${time.hours}`));
我承认这确实有些冗长。
答案 2 :(得分:0)
我建议采用以下功能性方法
for(day in ['mon','tue','wed','thu','fri','sat','sun']){
this[day + 'Time'] = weekTimes.find(x => x.date === this[day])
.map(x => x.hours);
}