[英]Javascript for loop behaviour outputting the same result each iteration
I'll admit I'm a bit of a JS novice, and coming from a PHP background, my idea of scope is clearly different to Javascript's. 我承认我是一个JS新手,并且来自PHP背景,我对范围的理解显然与Javascript不同。
// There's a date set, so begin processing
var original_date = new Date($('input#tour_encoded_dates').val());
var date_search_string = '';
var day_limit = 14;
var timestamp = '';
// Go forwards day_limit days
for(var i = 0; i < day_limit; i++) {
timestamp = strtotime('+'+i+' days', original_date);
calculated_date = new Date(timestamp).format('Y-m-d');
date_search_string += calculated_date + ' ';
}
console.log(date_search_string);
The output from console.log()
is: console.log()
的输出是:
2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10
I would have expected each iteration to increase the date by one day, but they remain the same. 我希望每次迭代都会将日期增加一天,但是它们保持不变。
For reference, if I change the final line of the loop to date_search_string += timestamp + ' ';
作为参考,如果我将循环的最后一行更改为date_search_string += timestamp + ' ';
the output is as follows: 输出如下:
1381363200000 1381363286400 1381363372800 1381363459200 1381363545600 1381363632000 1381363718400 1381363804800 1381363891200 1381363977600 1381364064000 1381364150400 1381364236800 1381364323200
So the issue is clearly with the calculated_date
variable - right? 所以问题显然出在calculated_date
变量上,对吗?
Can someone explain the proper way to do this? 有人可以解释这样做的正确方法吗? Thanks. 谢谢。
There is 86400 (ie 1/1000 day), between each timestamp. 每个时间戳之间有86400天(即1/1000天)。
You are computing (in strtotime
) as if timestamps were seconds but they are milliseconds. 您正在计算(在strtotime
),好像时间戳是秒,但它们是毫秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.