Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/402.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 将阵列保存并更新到本地存储JS_Javascript - Fatal编程技术网

Javascript 将阵列保存并更新到本地存储JS

Javascript 将阵列保存并更新到本地存储JS,javascript,Javascript,我试图将数组发送到本地存储,当我单击按钮并输入一个值时,元素被发送到本地存储中的数组,如下所示: ["info before reloading 1","info before reloading 2","info before reloading 3"] 如果我重新加载页面并在输入中写入一些内容,数组中的所有元素都将被删除,并使用我键入的新信息创建一个新数组,如下所示 ["new info 1","new info 2","new info 3"] ["info before reloa

我试图将数组发送到本地存储,当我单击按钮并输入一个值时,元素被发送到本地存储中的数组,如下所示:

["info before reloading 1","info before reloading 2","info before reloading 3"]
如果我重新加载页面并在输入中写入一些内容,数组中的所有元素都将被删除,并使用我键入的新信息创建一个新数组,如下所示

["new info 1","new info 2","new info 3"]
 ["info before reloading 1","info before reloading 2","info before reloading 3", "new info 1","new info 2","new info 3"];
我怎样才能避免删除初始信息,而阵列只是像这样更新并保存在本地存储中

["new info 1","new info 2","new info 3"]
 ["info before reloading 1","info before reloading 2","info before reloading 3", "new info 1","new info 2","new info 3"];
谢谢你的帮助

var mydiv=document.queryselectoral(“.div_btn”);
console.log(mydiv);

对于(i=0;i在将数据保存到本地存储时,必须首先使用
localStorage.getItem
获取
localStorage
数据

如果存在数据,则将数据添加到
mi_数组
,否则将数组保留为空

在当前代码中,您将忽略旧数据并仅用新数据替换数组

试试这个

var mydiv = document.querySelectorAll(".div_btn");
console.log(mydiv);
for (i = 0; i < mydiv.length; i++) {
    mydiv[i].addEventListener("click", function () {
        var parent = this.parentElement;
        console.log(parent.firstElementChild.innerHTML);
    });
}

var btn_local = document.getElementById("btn_local");
var user_name = document.getElementById("user_name");
var mi_array = [];
btn_local.addEventListener("click", function () {
    var name_value = user_name.value;
    if (name_value !== "") {
        // Get the data from localStorage
        let currentData = localStorage.getItem("usuarios");
        // Check the data if its not null
        mi_array = currentData ? JSON.parse(currentData) : [];
        mi_array.push(name_value);
        var json_transform = JSON.stringify(mi_array);
        localStorage.setItem("usuarios", json_transform);
    }
})
var mydiv=document.queryselectoral(“.div_btn”);
console.log(mydiv);
对于(i=0;i
请参见
var-mi_-array=JSON.parse(localStorage.getItem('usuarios')| |'[]);
在执行
var-mi_-array=[];
操作时,始终创建新的空数组,并且从不检查当前的内容storage@Sohaill事实上,我是新来的,我不理解这行代码mi_array=currentData?JSON.stringify(currentData):[];当我尝试使用您的代码时,始终获取mi_array.push不是一个函数