G
G
Gregory2019-12-27 14:09:12
JavaScript
Gregory, 2019-12-27 14:09:12

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'))
    }

Why is favorites defined as a string and not as an array?
in the future, based on this error, push does not work

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gregory, 2019-12-27
@gtomilin

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 question

Ask a Question

731 491 924 answers to any question