简体   繁体   中英

Push Objects into an array in Jquery

I'm trying to fill an array with objects, but the array is not filling properly. The last value is set in all positions of the array. Here's the code:

 var matrixprice = 5; var qualifiedDate = '2019-10-01'; var today = new Date(); var qDate = new Date(qualifiedDate); var nextDay = qDate; var myObject = new Object(); var myArray = []; var dailybonus = matrixprice * 0.03; var full_bonus = matrixprice * 2; var i = 0; while (i <= full_bonus) { nextDay.setDate(nextDay.getDate() + 1); i += dailybonus; myObject.title = '$' + i; myObject.start = nextDay; myArray.push(myObject); } var myString = JSON.stringify(myArray); console.log(myString);

The array Im getting is filled with only 1 value in all positions it looks like this:

[{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},           {"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"}]

Thank you in advance!

Update your while loop to push a new object:

while(i <= full_bonus){
    nextDay.setDate(nextDay.getDate()+1); 
    i += dailybonus;

    myArray.push({title: '$'+i, start: new Date(nextDay)});
}

Here's the full, working example:

 var matrixprice = 5; var qualifiedDate = '2019-10-01'; var today = new Date(); var qDate = new Date(qualifiedDate); var nextDay = qDate; var myArray = []; var dailybonus = matrixprice * 0.03; var full_bonus = matrixprice * 2; var i = 0; while(i <= full_bonus){ nextDay.setDate(nextDay.getDate()+1); i += dailybonus; myArray.push({title: '$'+i, start: new Date(nextDay)}); } var myString = JSON.stringify(myArray); console.log(myString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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