I have the below JSON, which is linked to a google calendar. The function setAllEvenDates(arrEvents)
loops through all the array but instead of giving the first item of the array give me the last. My intention is to get the first item of the array. How do I achieve that?
var arrElements = [
{ "name": "Electron", "eventdate": "" },
{ "name": "Falcon 9 B5", "eventdate": "" },
{ "name": "New Shepard", "eventdate": "" },
{ "name": "SpaceShipTwo", "eventdate": "" },
{ "name": "Gaofen 14", "eventdate": "" }
];
function setAllEvenDates(arrEvents) {
for (var i = 0; i < arrEvents.length; i++) {
setEventDate(arrEvents[i].name, arrEvents[i].eventdate);
break;
}
}
2
Answers
You can get the first item of the array without a for loop.
Using the for loop you are scrolling the entire array, but is not nececcary if you need only a specific element knowing what element is. You can get any element using array[index] where the index is from 0 to array.length – 1
You don’t even need to define a function for performing
setEventDate()
method.You can do,
If you really want to use the loop,