【发布时间】:2020-11-27 13:09:46
【问题描述】:
所以我正在开发一个应用程序,它接收来自用户的数据并将其作为对象存储在数组中,然后我创建了将这些数据存储在 localStorage 中的功能。这是我正在尝试做的基本演示:
// constructor function
function Book(title, author, pages, read = false) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
this.status = function() {
console.log(this.read);
}
}
// array to store objects
let mybooks = [];
// instances of the Book object
let book1 = new Book('Hello', 'John', 123, true);
let book2 = new Book('Hey', 'Jane', 13, false);
let book3 = new Book('Hi', 'Mary', 12, true);
let book4 = new Book('Holo', 'Peter', 10, false);
let book5 = new Book('Banda', 'Banda', 03, true);
// push the instances to the mybooks array
mybooks.push(book1);
mybooks.push(book2);
mybooks.push(book3);
mybooks.push(book4);
mybooks.push(book5);
// store mybooks to the localStorage
localStorage.mybooks = JSON.stringify(mybooks);
// retrieve data from the localStorage
let data = JSON.parse(localStorage.getItem('mybooks'));
// call the status() method on each object
data.forEach(book => {
book.status();
});
通过在每个对象上调用 .status() 方法,我希望在控制台上获得布尔 (true/false) 值。但我得到这个错误:
Uncaught TypeError: book.status is not a function
at app.js:36
at Array.forEach (<anonymous>)
at app.js:35
但如果我在将每个对象存储到 localStorage 之前对每个对象运行相同的函数,我会得到正确的输出。
【问题讨论】:
-
localStorage 存储文本,而不是对象。将数据存储在 json 中并使用存储的数据重新创建对象
标签: javascript json data-structures local-storage instance