我一直致力于通过循环生成一个包含十局(具有开始和结束时间的对象)的数组的函数。例如。
你明白了。时间与Moment.js保持一致。
我编写了我希望处理此代码的代码,但功能已被破坏。请参阅底部的功能逻辑说明。这是JSFiddle demonstrating the code and results,这是函数:
//Define the Game's Time Frame
var Game = new Object(); // Object that holds all game data
var end = { // what time does the game end?
"moment": moment().days(6).hour(0).minute(0).second(0)
};
var beginning = { // what time does the game start?
"moment": moment().days(1).hour(0).minute(0).second(0)
};
// I'm going to over-do the commenting here for debugging:
// assign start and end times to each of 10 innings
function generateInnings() {
// create an inning object to assign start and end to
var inning = new Object();
// create array to assign each of 10 inning objects to
Game.innings = new Array();
// shortcut for calculating game time span
var gameHours = 120;
// ten innings in a game. how many hours each?
var inningHours = gameHours / 10;
// for 10 intervals of x, generate each inning
for (x = 0; x < 10; x++) {
//inning starts when?
inning.start = beginning.moment.add("hours", (inningHours * x));
// inning ends when?
inning.end = inning.start.add("hours", inningHours);
// attach inning object to Game.innings array
Game.innings[x] = inning;
// JSFiddle Output
log("Inning " + x + " Starts: " + inning.start.calendar());
// JSFiddle Output
log("Inning " + x + " Ends: " + inning.end.calendar());
}
}
generateInnings();
结果:
导致此(非常)错误输出的原因是什么?
功能逻辑(这不是代码,但注释):
beginning = 12:00AM Mon
for (x=0;x<10;x++){ //do this x10
start = beginning plus (12hrs * current loop interval)
console.log("Inning" + current loop interval + " start: " + start);
}
对于x = 0,开始=开始+(12 * 0)小时// =仍然是星期一12:00 AM
对于x = 1,开始=开始+(12 * 1)小时// =星期一12:00 PM
对于x = 2,开始=开始+(12 * 2)小时// =星期二12:00 AM
我以为我已经构建了一个非常可靠,基本的功能。我只是在逻辑中看不到问题,它必须是Moment语法。
答案 0 :(得分:0)
问题在于:
inning.end = inning.start.add("hours", inningHours);
add()
方法不返回值,而是修改它自己的对象,因为moments are mutable。
相反,请执行:
inning.end = moment(inning.start).add("hours", inningHours);