This code is about storing data in localStorage. If localStorage is yet empty I want to create an array of such type:
(Key:)Events (Value:)[{Date: "", Event: "", Participants: "", Description: ""}]
If there's yet some data in localStorage then runs the code else if...
if (tdAttr) {
var fastDate = tdAttr.getAttribute('data-cell');
var fastEvent = fastAddEvent.value;
var events = JSON.parse(localStorage.getItem('events')) || [];
localStorage.setItem('events', JSON.stringify(events));
var addFastEvent = function () {
if (events.length == 0) {
//JS doesn't see the "events" variable inside this scope
} else if (events.length > 0) {
for (var i = 0; i < events.length; i++) {
if (events[i].Date == fastDate) {
events[i].Event = fastEvent;
events[i].Participants = "";
events[i].Description = "";
};
break;
};
};
localStorage.setItem('events', JSON.stringify(events));
};
addFastEvent();
};
So, issue #1: Why doesn't JS define the events variable inside the firts if condition (console.log:
Uncaught TypeError: Cannot read property 'length' of undefined
)?
Though after else if... it does.
Issue #2: How do I create my array
(Key:)Events (Value:)[{Date: "", Event: "", Participants: "", Description: ""}]
inside the first if condition? I tried
if (events.length == 0) {
var events = [];
arr.push({
Date: fastDate,
Event: fastEvent,
Participants: "",
Description: ""
});
}
But it still doesn't see the variable events (even inside the if condition) and shows me the error.
UPD I managed to solve the issue #2:
if (events.length == 0) {
localStorage['events'] = events.push({
Date: fastDate,
Event: fastEvent,
Participants: "",
Description: ""
});
}
Though, still can't understand why the variable is "invisible" inside the first if condition. Let's say, there's no stored items when the condition starts to check, but I understand my variable
var events = JSON.parse(localStorage.getItem('events')) || [];
like this - We get stored items, if there are no stored items, we create an array. It seems like JS understands it like - We get stored items or an existing yet array