Reputation: 27048
I am using Date.js to display some dates and a weird thing happens. If I use it in an array formed from within an each
statement.
Here is what i mean:
If I pass and use the events_array
to the test
function array everything works fine, but if I use the eventsArray
one, that should look the same, I get:
startDate is undefined
...new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate()).getTime()...
function getTest() {
$.ajax({
type: "GET",
url: "/index",
dataType: "json",
success: function (data) {
var eventsArray = new Array();
jQuery.each(data, function (i, val) {
eventsArray.push(
new Array({
startDate: new Date(2011, 07, 20, 15, 50),
endDate: new Date(2012, 00, 10),
}));
});
var events_array = new Array({
startDate: new Date(2011, 07, 20, 15, 50),
endDate: new Date(2012, 00, 10),
}, {
startDate: new Date(2011, 07, 20, 15, 50),
endDate: new Date(2012, 00, 10),
});
test(events_array);
}
});
}
Any ideas?
Thanks
Upvotes: 0
Views: 128
Reputation: 2288
your two arrays are not identicals : var eventsArray = new Array();
jQuery.each(data, function (i, val) {
eventsArray.push(
new Array({
startDate: new Date(2011, 07, 20, 15, 50),
endDate: new Date(2012, 00, 10),
}));
});
/* here eventsArray is like that [[{
startDate: new Date(2011, 07, 20, 15, 50),
endDate: new Date(2012, 00, 10),
}]] Look at the two [[ or ]] : array of object in an array
*/
var events_array = new Array({
startDate: new Date(2011, 07, 20, 15, 50),
endDate: new Date(2012, 00, 10),
}, {
startDate: new Date(2011, 07, 20, 15, 50),
endDate: new Date(2012, 00, 10),
});
/* here events_array is like that [{
startDate: new Date(2011, 07, 20, 15, 50),
endDate: new Date(2012, 00, 10),
}, {}] only one [ ... array of objects ...
*/
i think you should use :
eventsArray.push({
startDate: new Date(2011, 07, 20, 15, 50),
endDate: new Date(2012, 00, 10)
}); });
Hope this helps
Upvotes: 1
Reputation: 87073
Within your test function try following:
function test(eventsArray) {
// try this
eventsArray[0][0].startDate
}
eventsArray
looks like following:
eventsArray = [
[
{
startDate: ..
endDate: ..
}
]
];
But you should make it easier:
var eventsArray = new Array();
eventsArray.push({
startDat: ..
endDate: ..
});
Don't use additional array within eventsArray
if you not need it.
and to access that values use:
eventsArray[0].startDate;
eventsArra[0].endDate;
events_array
, you'll see that, you're not using additional array when you push data within it.Upvotes: 2
Reputation: 115950
You probably meant to fill eventArray
with objects, not arrays with a single object in each one:
eventsArray.push({ // NOT new Array...
startDate: new Date(2011, 07, 20, 15, 50),
endDate: new Date(2012, 00, 10)
}); });
Upvotes: 1