Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Localstorage仅保存最后一个对象(脚本)_Javascript_Local Storage - Fatal编程技术网

Javascript Localstorage仅保存最后一个对象(脚本)

Javascript Localstorage仅保存最后一个对象(脚本),javascript,local-storage,Javascript,Local Storage,我想在OOP中创建一个带有图书列表的应用程序,但在localstorage中保存列表时遇到问题。我让该用户可以添加他的图书,现在我想将其保存到本地存储中。我制作了一个数组,并将对象保存到其中,但有些东西不起作用。我只得到最新的东西,我不知道为什么 一段js: var title = document.querySelector('input#title').value; var author = document.querySelector('input#author').val

我想在OOP中创建一个带有图书列表的应用程序,但在localstorage中保存列表时遇到问题。我让该用户可以添加他的图书,现在我想将其保存到本地存储中。我制作了一个数组,并将对象保存到其中,但有些东西不起作用。我只得到最新的东西,我不知道为什么

一段js:

    var title = document.querySelector('input#title').value;
    var author = document.querySelector('input#author').value;
    var status = document.querySelector('select').value;
    var table = document.querySelectorAll('.table')[1];
    var book = new Book(title, author, status);
    obj.push(book);
    localStorage.setItem('Array',JSON.stringify(obj));

您正在使用键“Array”覆盖上一个localStorage项

存储接口的setItem()方法在传递一个键名和值时,会将该键添加到给定的存储对象中,或者更新该键的值(如果该键已经存在),因此在您的情况下会更新以前的localstorage项。。 如果要解决此问题,需要使用以前尝试的值,需要使用唯一键。 也许我喜欢跑步

localStorage.setItem(`Array-${id}`,JSON.stringify(obj));

由于每次使用setItem时都使用相同的键,因此localStorage将覆盖该值。我认为您遇到的问题与如何初始化obj数组有关。如果您有一个将图书列表/数组保存到localStorage的函数,那么请确保在该函数之外初始化obj。查看下面的示例

功能手册(标题、作者、状态){
this.title=标题;
this.author=作者;
这个状态=状态;
}

var obj=[];// 确保使用以前的值初始化
obj

let obj = JSON.parse(localStorage.getItem('Array'));
...

执行类似于从本地获取数组值的操作,然后在其中添加项

const-array=JSON.parse(localStorage.getItem('array'))||[];
课堂用书{
构造函数(标题、作者、状态){
this.title=标题;
this.author=作者;
这个状态=状态;
}
}
document.getElementById(“推送项”).addEventListener(“单击”,函数(){
控制台日志(“推”);
var title=document.querySelector('input#title')。值;
var author=document.querySelector('input#author')。值;
变量状态=document.querySelector('select')。值;
var table=document.querySelectorAll('.table')[1];
var图书=新书(标题、作者、状态);
数组。推(书);
setItem('Array',JSON.stringify(Array));
});

1.
2.

推送
如何初始化obj?