我有一个非常奇怪的问题与Javascript。 我试图循环我的日期来做一些检查并为我的数组添加值,但是当我返回数组时,它会显示我的所有集合的最后一个值。 以下是我的代码:
function myFunction() { var todayDate = new Date(); var firstDay = new Date(todayDate.getFullYear(), todayDate.getMonth(), 1); var lastDay = new Date(todayDate.getFullYear(), todayDate.getMonth() + 1, 0); var testDates=[]; while (firstDay <= lastDay) { var currentDate = firstDay; testDates.push( firstDay); firstDay.setDate(firstDay.getDate() + 1); } document.getElementById("demo").innerHTML = testDates; }这最终是我所有日期的最后一个值:
2016年1月1日星期五00:00:00,2016年1月1日星期五00:00:00,2016年1月1日星期五00:00:00,2016年1月1日星期五00:00:00,2016年1月1日星期五00:00:00,星期五Jan 01 2016 00:00:00
为什么会发生?
I have a very weird issue with Javascript. I am trying to loop through my date to do some checking and add value to my array, but when I return out the arrays, it shows all my collections with last value. Below is my code:
function myFunction() { var todayDate = new Date(); var firstDay = new Date(todayDate.getFullYear(), todayDate.getMonth(), 1); var lastDay = new Date(todayDate.getFullYear(), todayDate.getMonth() + 1, 0); var testDates=[]; while (firstDay <= lastDay) { var currentDate = firstDay; testDates.push( firstDay); firstDay.setDate(firstDay.getDate() + 1); } document.getElementById("demo").innerHTML = testDates; }This ends up with last value for all my dates:
Fri Jan 01 2016 00:00:00,Fri Jan 01 2016 00:00:00,Fri Jan 01 2016 00:00:00,Fri Jan 01 2016 00:00:00,Fri Jan 01 2016 00:00:00,Fri Jan 01 2016 00:00:00
Why does this happen?
最满意答案
您不会将日期添加到数组中,而是对日期的引用。 然后,如果更新firstDay ,则更新数组中所有元素的日期。 (因为它们都指向同一个日期)。 尝试克隆这样的日期:
function myFunction() { var todayDate = new Date(); var firstDay = new Date(todayDate.getFullYear(), todayDate.getMonth(), 1); var lastDay = new Date(todayDate.getFullYear(), todayDate.getMonth() + 1, 0); var testDates=[]; while (firstDay <= lastDay) { var currentDate = firstDay; testDates.push( new Date(firstDay.getTime()) ); firstDay.setDate(firstDay.getDate() + 1); } document.getElementById("demo").innerHTML = testDates; }You are not adding the date to your array, but a refference to the date. Then if you update the firstDay, you update the date of ALL elements in the array. (Because they all point to the same date). Try to clone the date like this:
function myFunction() { var todayDate = new Date(); var firstDay = new Date(todayDate.getFullYear(), todayDate.getMonth(), 1); var lastDay = new Date(todayDate.getFullYear(), todayDate.getMonth() + 1, 0); var testDates=[]; while (firstDay <= lastDay) { var currentDate = firstDay; testDates.push( new Date(firstDay.getTime()) ); firstDay.setDate(firstDay.getDate() + 1); } document.getElementById("demo").innerHTML = testDates; }更多推荐
发布评论