使用Moment.js的JS间隔生成函数:意外输出
JS interval generation function with Moment.js: Unexpected output
我一直在研究一个函数,该函数通过循环生成一个包含十个Innings (具有开始和结束时间的对象)的数组。例如,
- 比赛于周一12:00开始,于周六12:00结束
- 比赛由10局12小时的比赛组成
- 第1局从星期一中午12点开始,到当天中午12点结束,第2局开始。
你懂的。时间是用Moment.js保存的。
我已经写了代码,我希望处理这个,但功能是坏的。请参阅底部的函数逻辑注释。下面是演示代码和结果的JSFiddle,下面是函数:
//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();
结果:
- 第0局开始:上周一中午12:00
- 第0局结束:上周一下午12:00
- 第一局开始:上周二中午12:00
- 第一阶段结束:上周二下午12:00
- 第二局开始:上周四上午12:00
- 第二阶段结束:上周四上午12:00
- …我们还需要走得更远吗?
是什么导致这个(非常)不正确的输出?
函数逻辑(这不是代码,而是注释):
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);
}
for x = 0, start = beginning + (12 * 0) hours//= still Monday 12:00 AM
for x = 1, start = beginning + (12 * 1) hours//= Monday 12:00 PM
for x = 2, start = beginning + (12 * 2) hours//= Tuesday 12:00 AM
我认为我已经构建了一个非常可靠的基本函数。我只是看不出逻辑上的问题,它一定是Moment语法。
问题就在这里:
inning.end = inning.start.add("hours", inningHours);
add()
方法不返回一个值,但是修改它自己的对象,因为矩是可变的。
相反,做的事:
inning.end = moment(inning.start).add("hours", inningHours);
相关文章:
- Node.js使用Series函数(模式?)实现流控制时出现意外结果
- 在一个函数中,我有一个未捕获的语法错误:意外的标记else
- Javascript:函数返回意外结果
- Javascript 数组反向函数意外行为
- HTML 无法识别我要求它运行的 javascript 文件,语法错误:意外的令牌“<”(匿名函数)script.js:
- QML:Lambda 函数意外工作
- 意外的“else”和函数未运行
- 一个javascript函数导致“;意外标识符”;来自不同函数的错误
- Underscore.js:具有_.object函数的意外行为
- JavaScript自定义函数返回意外值
- 调用加载的顺序函数会意外中断代码
- 使用'时出现意外的T_FUNCTION;回调'=>函数($resp)
- JavaScript - 意外/奇怪的构造函数
- 未捕获的语法错误:意外的标记^(匿名函数)
- jQuery模块函数意外返回'未捕获的类型错误'
- PHP调用脚本函数,返回值为Uncaught SyntaxError:意外的令牌ILLEGAL
- .css函数意外令牌非法 jquery
- 主干渲染函数:意外令牌非法
- jQuery函数-意外行为
- 使用Moment.js的JS间隔生成函数:意外输出