简体   繁体   English

循环和数组推送的JavaScript

[英]javascript for loop and array pushing

I'm trying to create an array of date objects starting from a certain date up till today. 我正在尝试创建从某个日期开始直到今天的日期对象数组。

Here's the code I have: 这是我的代码:

var beginning = new Date("04,06,2013");

var dates = [];
var today = new Date();

while (beginning < today){
    var x = beginning; 
    console.log(x);
    dates.push(x);
    beginning.setDate(beginning.getDate()+1)
}

for (var i in dates) {
  console.log(dates[i]);
}

In the while loop I see the correct dates incrementing but when I print out the dates in the array at the last for loop I see all the dates that are pushed being today's date. 在while循环中,我看到正确的日期在递增,但是当我在最后一个for循环中打印出数组中的日期时,我看到所有推入的日期都是今天的日期。

Any ideas? 有任何想法吗?

What your code does is push a whole bunch of references to the exact same Date object. 您的代码要做的是将一堆引用推送到完全相同的Date对象。 So, you have an array full of all the same Date object and each time you change that object, all elements in the array just point to the same object so they will all appear to change. 因此,您拥有一个由所有相同的Date对象组成的数组,并且每次更改该对象时,数组中的所有元素都指向同一对象,因此它们看上去都将发生变化。

When you push an object into an array or assign an object to a variable, it does not make a copy, it pushes a reference to it (think of it like a pointer in other languages). 当您将对象推入数组或将对象分配给变量时,它不会产生副本,而是会推向它的引用(像其他语言中的指针一样,将其想到)。 To push different date objects for each iteration of the loop, you'd have to create a new date object each time through the loop and push that. 要为循环的每次迭代推送不同的日期对象,您每次都要在循环中创建一个新的日期对象并将其推送。

In javascript, assigning an object or an array to any variable (which includes pushing it into an array) only assigns a reference to that object or array, not a copy. 在javascript中,将对象或数组分配给任何变量(包括将其推入数组)仅分配对该对象或数组的引用,而不是副本。 This is a common issue that bits most people coming up to speed on javascript. 这是一个普遍的问题,大多数人无法使用javascript。

You can make a new date object each time through the loop like this: 您可以每次通过循环创建一个新的日期对象,如下所示:

var beginning = new Date("04,06,2013");

var dates = [];
var today = new Date(), x;

while (beginning < today){
    x = new Date(beginning.getTime()); 
    console.log(x);
    dates.push(x);
    beginning.setDate(beginning.getDate()+1)
}

You're only working with one single Date instance throughout all that code. 在所有这些代码中,您仅使用一个Date实例。

To create a copy of a Date, do this: 要创建日期的副本,请执行以下操作:

x = new Date(beginning.getTime());

Then call the .setDate() method to move it forward. 然后调用.setDate()方法将其向前移动。

The setters on JavaScript Date instances change the object. JavaScript Date实例上的设置器更改对象。 They don't create a new one. 他们不会创建新的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM