【问题标题】:How to check if value exist in Local Storage data set?如何检查本地存储数据集中是否存在值?
【发布时间】:2017-11-08 05:14:36
【问题描述】:

我对本地存储进行了一些研究。似乎是存储数据的一个不错的选择。在我的单页应用程序中,我使用 JSON 来存储在我的应用程序中多次使用的一些数据。我想知道是否可以用本地存储替换 JSON?还有什么好处?到目前为止,我能够在本地存储中加载数据,但我无法检查本地存储中是否存在值以及我将如何读取数据。这是一个例子:

$.ajax({
        type: 'POST',
        url: 'App.cfc?method='+getMethod,
        data: {'recID':recID},
        dataType: 'json'
    }).done(function(obj){
        var numRecs = obj.RECORDCOUNT;
        jsonData[recID] = obj.DATA;
        localStorage.setItem(recID,JSON.stringify(obj.DATA));

        var firstN = jsonData[recID].hasOwnProperty('F_NAME') == true ? $.trim(jsonData[recID]['F_NAME']['value']) : '',
        lastN = jsonData[recID].hasOwnProperty('L_NAME') == true ? $.trim(jsonData[recID]['L_NAME']['value']) : '';
        console.log(localStorage[recID] +'\n'+ localStorage[recID].hasOwnProperty("L_NAME")); //Check Local Storage if value exist

    }).fail(function(jqXHR, textStatus, errorThrown){
    if(jqXHR.status == 0){
        alert("Fail to connect. Please check your internet connection.");
    }else{
        alert("Error: "+errorThrown);
    }
});

以下是 JSON 和 localStorage 数据的示例:

{"F_NAME":{"value":"John"},"L_NAME":{"value":"Smith"}}

在我将数据转储到控制台后,JSON 和本地存储具有相同的结构,但hasOwnProperty() 在上面的代码示例中表示false,我在控制台中测试 loacl 存储。我想知道我的代码是否无效或其他原因导致我的代码失败。我想使用本地存储的主要原因是用户断开互联网连接的情况。在这种情况下,我想以用户不会丢失数据的方式将表单数据保存在本地存储中。如果有人可以提供任何提示的示例或帮助,请告诉我。谢谢!

【问题讨论】:

  • 您可以通过输入 localStorage 在控制台中检查本地存储。在 Chrome 中,您还可以从开发人员工具的应用程序选项卡中查看您的 localStorage 数据。请注意,本地存储为每个键存储一个项目。如果您想将 JSON 对象存储在特定键中,请确保您先 JSON.stringify() 并在您想要访问信息时对其进行解析。

标签: javascript jquery json local-storage


【解决方案1】:

localStorage 存储 字符串,因为您在保存时已经在 JSON.stringify()ing 中了。但是你需要更换你的支票

localStorage[recID].hasOwnProperty("L_NAME")

JSON.parse(localStorage[recID]).hasOwnProperty("L_NAME")

编辑:您有一个整个对象,您将其存储为localStorage[recID],因此您需要对其进行解析,然后访问生成的对象,例如:

const record = JSON.stringify({
  "F_NAME": {
    "value": "John"
  },
  "L_NAME": {
    "value": "Smith"
  }
});

console.log(JSON.parse(record)['F_NAME']['value'])

JSON.parse(record) 成为对象,然后您访问其后代参数['F_NAME']['value']。括号的位置很关键。

【讨论】:

  • 如何访问 localStorage 中的 L_NAME 值?我试过了,但代码失败了: $.trim(JSON.parse(localStorage[recID]['F_NAME']['value']))
  • 我看到括号的位置非常重要,即使看起来不常见:)
  • 这是因为您没有解析localStorage[recID]['F_NAME']['value'],您正在解析 localStorage[recID]。如果有帮助,您可以接受它:)
猜你喜欢
  • 1970-01-01
  • 2017-04-23
  • 2012-10-13
  • 2022-11-18
  • 2015-11-05
  • 1970-01-01
  • 2019-06-07
  • 1970-01-01
  • 2019-05-03
相关资源
最近更新 更多