我正在制定预订系统,而价格取决于季节,而且这些季节每年都会重复出现。到目前为止,除了经常出现的季节,一切都很顺利。我正在使用moment.js和moment-range插件,但这似乎不会导致我遇到的问题。因为没有其他方法可以使用具有重复范围的时间范围,我认为只需迭代我的seasonsObject并为连续五年(或任何数字)年创造新的季节。基本上,这就是我被困住的地方:我无法让循环按预期工作。
var seasonsObject = {
low: {
period: "low",
seasonStart: "2017-11-01T12:01:00.000Z",
seasonEnd: "2018-03-15T12:01:00.000Z"
},
high: {
period: "high",
seasonStart: "2018-06-01T12:01:00.000Z",
seasonEnd: "2018-08-01T12:01:00.000Z"
}
}
var futureSeasons;
for (var i = 0; i < 5; i++) {
futureSeasons = _.each(seasonsObject,(val) => {
val.range = moment.range(moment(val.seasonStart).add(i,'y'), moment(val.seasonEnd).add(i,'y'))
});
}
我测试了依赖于moment.js和moment-range的部分,所以我确定我的循环不能正常工作 - 它似乎在i = 0
后突破,因为我仍然只看到第一年的季节。我还尝试使用_.map()
和_.mapObject()
代替_.each()
,但这两项工作都没有。
但是,所需的输出将是:
futureSeasons: {
low0: {
period: "low",
seasonStart: "2017-11-01T12:01:00.000Z",
seasonEnd: "2018-03-15T12:01:00.000Z"
},
high0: {
period: "high",
seasonStart: "2018-06-01T12:01:00.000Z",
seasonEnd: "2018-08-01T12:01:00.000Z"
},
low1: {
period: "low",
seasonStart: "2018-11-01T12:01:00.000Z",
seasonEnd: "2018-03-15T12:01:00.000Z"
},
high1: {
period: "high",
seasonStart: "2019-06-01T12:01:00.000Z",
seasonEnd: "2018-08-01T12:01:00.000Z"
},
low2: {
period: "low",
seasonStart: "2020-11-01T12:01:00.000Z",
seasonEnd: "2018-03-15T12:01:00.000Z"
},
high2: {
period: "high",
seasonStart: "2021-06-01T12:01:00.000Z",
seasonEnd: "2018-08-01T12:01:00.000Z"
},
...
}
我正在使用 Vue.js 并尝试将该行为包装在计算属性中!任何帮助高度赞赏: - )
答案 0 :(得分:0)
这是你想要做的吗?
window['moment-range'].extendMoment(moment);
var seasonsObject = {
low: {
period: "low",
seasonStart: "2017-11-01T12:01:00.000Z",
seasonEnd: "2018-03-15T12:01:00.000Z"
},
high: {
period: "high",
seasonStart: "2018-06-01T12:01:00.000Z",
seasonEnd: "2018-08-01T12:01:00.000Z"
}
}
function makeFutureSeasons(count) {
const futureSeasons = {};
_.range(0, count).forEach(y => {
Object.keys(seasonsObject).forEach(k => {
const {
period,
seasonStart,
seasonEnd
} = seasonsObject[k];
futureSeasons[k + y] = {
period,
seasonStart: moment(seasonStart).add(y, 'years').toISOString(),
seasonEnd: moment(seasonEnd).add(y, 'years').toISOString()
};
});
});
return futureSeasons;
}
const fseasons = makeFutureSeasons(5);
console.log(fseasons);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/3.1.1/moment-range.min.js"></script>