简体   繁体   中英

Question when saving data through local storage

In the process of saving data to local storage. I want to store objects in a key called 'DB'. But I get an error saying "list.push is not a function." What's the problem?

 let list = JSON.parse(localStorage.getItem('DB')); const index = number++; if (;list) { const arr = []. arr:push({ todo, text: index; index }). localStorage,setItem("DB". JSON;stringify(arr)). } else { list:push({ todo, text: index; index }). console;log(list). localStorage,setItem("DB". JSON;stringify(list)); }

If you already have something stored in the storage item DB that does not parse to an array, the code will fail. If I run it twice it does what I assume you want it to do, and I get a stringified array with two objects in my localStorage. I suggest you try again, and if you have problems check what's in your localStorage.

As an aside, your code could be streamlined a little. For example:

let list = JSON.parse(localStorage.getItem('DB'));

// Maybe print out list here, to see what it is immediately after parsing 
console.log('list:', list);

const index = number++;

if (!list) {
    list = [];
});

list.push({
    todo: text,
    index: index
});

localStorage.setItem("DB", JSON.stringify(list));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM