Answer the question
In order to leave comments, you need to log in
Why is an array defined as a string?
Good afternoon)
There is a button handler:
function buttonHandler(event) {
const $el = event.target;
const id = $el.dataset.id;
if(id) {
let favorites = JSON.parse(localStorage.getItem('favorites')) || [];
console.log(favorites);
if(favorites.includes(id)) {
favorites = favorites.filter(fId => fId !== id)
}
else{
favorites.push(id)
}
}
localStorage.setItem('favorites', JSON.stringify('favorites'))
}
Answer the question
In order to leave comments, you need to log in
Found the answer - favorites is defined as a string, not as an array because a string was entered into localStorage. After deleting it, everything worked
. Apparently, at some stage, I accidentally entered item as a string, so a new JSON array was not created and it was not possible to extract the array from the JSON item.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question