javascript - 如果我只使用整数作为键,如何在本地存储中获取最后插入的键?

标签 javascript php jquery serialization local-storage

我正在尝试构建注册表并使用本地存储来保存详细信息。在向 locastorage 添加另一个表单详细信息时,我想知道最后插入的键的值是多少,以便我可以递增它并可以插入具有递增键值的新记录。

如何实现。如果我删除任何记录,我当前的代码将覆盖这些值,因为我正在计算存储中可用的键数。

      function setlocal(){
      var o = {};
      var ff = $('#myform').serializeArray();

      $.each(ff, function() {
          if (o[this.name] !== undefined) {
              if (!o[this.name].push) {
                  o[this.name] = [o[this.name]];
              }
              o[this.name].push(this.value || '');
          } else {
              o[this.name] = this.value || '';
          }
      });
      var tt = JSON.stringify(o);
      localStorage.setItem(localStorage.length+1, tt);
      $('#afterInsert').text('data added sucessfully');
      return true;
  }

有什么建议吗?

最佳答案

为什么不能将最后插入的键存储在单独的属性中

var lastKey = parseInt(localStorage.getItem('lastKey'));
var newKey = lastKey + 1 || 1;
localStorage.setItem(newKey , tt);
localStorage.setItem('lastKey', newKey);

关于javascript - 如果我只使用整数作为键,如何在本地存储中获取最后插入的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22524049/

相关文章:

javascript - 如何让popup垂直上下展开

javascript - 如何在 SAPUI5 上检索字段值

javascript - jQuery ("#"+id) 对比 document.getElementById (""+id)

javascript - 如何将触发器/事件转换为 Promise 或异步/等待?

javascript - 如何在 html 或 javascript 中将 ID 更改为类

php - mysql_real_escape_string 问题

php - 通过 PHP 和 jQuery 将 MySQL 解析为 JavaScript 数组

javascript - 添加计时器以在将产品添加到购物车后关闭 Ajax Quick Cart (Shopify)?

jquery - 在模板中的剑道网格单元格中显示下拉菜单

javascript - 限制与 AngularJS 状态匹配的动态 URL 参数的最佳方法