1

I'm adding a value to each object in the object list. But I don't know why its adding the date for every object in every loop.

this is my code:

var emptyday: {
    "date":""
}

//make list of days in month
var monthlist = [];
for (i=0;i<=days_in_months;i++) {
    monthlist[i] = emptyday;
}

So in my example lets say that days_in_months is 31 (days)

Now comes the adding

for (x=1;x<=days_in_months;x++) {

    console.log(x);
    if (x<10) {
        daynumber = "0" + x;
    } else {
        daynumber = x;
    }

    datestring = year + "-"+ (month+1) + "-" + daynumber;

    dayofmonth = monthlist[x]; 
    dayofmonth["date"] = datestring;
            //monthlist[x].date = datestring;

}

When I try adding (dayofmonth["date"] = datestring or monthlist[x].date) it adds to all date values of all objects in every loop.

The console.log looks like this for the first loop:

[Object { date= "2013-1-01"}, Object { date= "2013-1-01"}, Object { date= "2013-1-01"}, Object { date= "2013-1-01"}, Object { date= "2013-1-01"}, Object { date= "2013-1-01"}, etc

for 31 times in the first loop

And in the last loop it will be 2013-1-31

I don't understand why it is adding that value to all objects. I have tried console.log and debugging all over the place to read out values and trying to understand what goes wrong, but still haven't found a solution

1 Answer 1

4

The references in your array all point to the same object. Javascript is pass by value. So when you do

//make list of days in month
var monthlist = [];
for (i=0;i<=days_in_months;i++) {
    monthlist[i] = emptyday;
}

the you are putting a copy of the reference emptyday at every position in the array. Since the copies of the reference all point to the same object literal, you have an array of references to one object.

You need to create a new object literal every time thru the list.

var monthlist = [];
for (i=0;i<=days_in_months;i++) {
    monthlist[i] = {
       date: ""
    };
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks! I was breaking my head with this! big "aha" moment here!
yay!. Understanding pass by value semantics will definitely help you going forward, and in other languages too -- when things in some sort of collection change that you don't expect, it's a likely culprit (although not necessarily the only culprit).
when you said the word "reference", everything was clicking in my mind.thanks! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.