如何使用localstorage删除数组中的对象?

时间:2017-05-22 06:52:26

标签: javascript local-storage

我必须删除数组中的对象,它应该从localstorage中删除。我试图通过使用splice方法删除它,但实际上没有获得如何使用它。 Folloeing是我试过的代码 -

 var details = [];



 function addEntry() {


   var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
   if (existingEntries == null) existingEntries = [];


   var srno = document.getElementById("txtpid").value;
   var name = document.getElementById("txtpname").value;
   var dob = document.getElementById("txtpdob").value;
   var email = document.getElementById("txtpemail").value;
   var address = document.getElementById("txtpaddr").value;
   var contact = document.getElementById("txtpmobile").value;

   var obbbj = {
     txtpid: srno,
     txtpname: name,
     txtpdob: dob,
     txtpemail: email,
     txtpaddr: address,
     txtpmobile: contact
   };
   localStorage.setItem("details", JSON.stringify(obbbj));

   existingEntries.push(obbbj);
   localStorage.setItem("allEntries", JSON.stringify(existingEntries));
   showEntry();
   console.log(existingEntries);
   //location.reload();
 }


 function showEntry() {
   var messageBox = document.getElementById("display");
   messageBox.value = "";
   document.getElementById("txtpid").value = "";
   document.getElementById("txtpname").value = "";
   document.getElementById("txtpdob").value = "";
   document.getElementById("txtpemail").value = "";
   document.getElementById("txtpaddr").value = "";
   document.getElementById("txtpmobile").value = "";


   var render = "<table border='1'>";
   render += "<tr><th>Srno</th><th>Name</th><th>Birthdate</th><th>Email</th><th>Address</th><th>Contact</th></tr>";


   var allEntriesoo = {};
   var detailsOOO = {};
   for (i = 0; i < localStorage.length; i++) {
     var key = localStorage.key(i);
     var person = localStorage.getItem(key);
     if (key == 'allEntries')
       allEntriesoo = JSON.parse(person);
     if (key == 'details')
       detailsOOO = JSON.parse(person);
     var data = JSON.parse(person);

   }

   for (var key in allEntriesoo) {
     console.error(allEntriesoo[key])
     render += "<tr><td>" + allEntriesoo[key].txtpid + "</td><td>" + allEntriesoo[key].txtpname + " </td>";
     render += "<td>" + allEntriesoo[key].txtpdob + "</td>";
     render += "<td>" + allEntriesoo[key].txtpemail + "</td>";
     render += "<td>" + allEntriesoo[key].txtpaddr + "</td>";
     render += "<td>" + allEntriesoo[key].txtpmobile + "</td>";
     render += "<td><input type='button' value='Delete' onClick='return deleteEntry(" + i + ")'></td>";
     render += "<td><input type='button' value='Edit' onClick='return editInfo(" + i + ")'></td></tr>";

   }
   render += "</table>";
   display.innerHTML = render;
 }

 function nameVal() {
   document.getElementById("txtpname").focus();
   var n = document.getElementById("txtpname").value;
   var r;
   var letters = /^[a-zA-Z]+$/;
   if (n == null || n == "") {
     alert("please enter user name");
     return null;
     n.focus();
   } else {
     if (n.match(letters) && n != "") {
       r = ValidateEmail();
       return r;
     } else {
       alert("please enter alphabates");
       document.getElementById("txtpname").value = "";
       document.getElementById("txtpname").focus();
       return null;
     }
   }
 }

 function ValidateEmail() {
   var uemail = document.getElementById("txtpemail").value;
   var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
   if (uemail.match(mailformat)) {
     return true;
   } else {
     alert("You have entered an invalid email address!");
     document.getElementById("txtpemail").value = "";
     document.getElementById("txtpemail").focus();
     return null;
   }
 }

 function alphanumeric() {
   var uadd = document.getElementById("txtpaddr").value;
   var letters = /^[0-9a-zA-Z]+$/;
   if (uadd == null || uadd == "") {
     alert("plz enter address");

     uadd.focus();
   } else {
     if (uadd.match(letters)) {
       return true;
     } else {
       alert('User address must have alphanumeric characters only');
       document.getElementById("txtpaddr").value = "";
       document.getElementById("txtpaddr").focus();
       return false;
     }
   }
 }

 function cntVal() {
   var n = document.getElementById("txtpmobile").value;
   var r1;
   var letters = /^\d{10}$/;
   if (n !== null || n !== "") {
     if (n.match(letters)) {
       r1 = alphanumeric();
       return r1;
     } else {
       alert("please enter contact number");
       document.getElementById("txtpmobile").value = "";
       document.getElementById("txtpmobile").focus();
       return null;
     }
   } else {
     alert("please enter contact Number");
     return null;
     n.focus();
   }

 }

 function deleteEntry(id) {
   console.log("aaaaaaaaaaaaaaAAAA");

   var entry = localStorage.getItem('allEntries') JSON.parse(localStorage.getItem('allEntries')): [];
   var index;
   for (var i = 0; i < entry.length; i++) {
     if (entry[i].id === id) {
       index = i;
       break;
     }
   }
   if (index === undefined) return
   entry.splice(index, 1);
   localStorage.setItem('entry', JSON.stringify(entry));
 }

 function clearstorage() {
   localStorage.clear();
   window.location.reload();
 }

 window.onload = function() {
   showEntry();
 };

2 个答案:

答案 0 :(得分:0)

在您的deleteEntry函数中,您在localStorage中设置了一个名为&#39; entry&#39;的新项目。所以你没有设置allEntries&#39;这可能就是为什么它会像那样出现的,所有的东西都是&#39;尚未更新。所以只需再次设置所有条目。 localStorage.setItem(&#39; allEntries&#39;,JSON.stringify(entry));

你也错过了&#39;?&#39;为你变量&#39;条目&#39; ...

var entry = localStorage.getItem(&#39; allEntries&#39;)? JSON.parse(localStorage.getItem(&#39; allEntries&#39;)):[]; &lt; - 它应该是这样的。

与“if else声明”相同,

&#13;
&#13;
function deleteEntry(id){
    console.log("aaaaaaaaaaaaaaAAAA");

      var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : [];
        var index;
        for (var i = 0; i < entry.length; i++) {
            if (entry[i].id === id) {
              index=i;
              break;
            }
        }
        if(index === undefined) return 
        entry.splice(index, 1);
        localStorage.setItem('allEntries', JSON.stringify(entry)); <--- like this

    }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用创建临时对象,然后在localStorage中替换它。

 function deleteEntry(id){
    console.log("aaaaaaaaaaaaaaAAAA");

      var entry = JSON.parse(localStorage.getItem('allEntries'));
        var temp= [];
        for (var i = 0; i < entry.length; i++) {
            if (entry[i].id !== id) {
              temp.push(entry[i]);
            }
        }
        localStorage.setItem('entry', JSON.stringify(temp));
    }