gpt4 book ai didi

javascript - 将本地存储中的对象存储到变量中

转载 作者:行者123 更新时间:2023-11-28 03:25:42 25 4
gpt4 key购买 nike

我正在尝试从本地存储中检索一个对象并将其加载到一个变量中。我怎样才能做到这一点 ?这就是我卡住的地方

   var messageStorage={};
messageStorage.retrieve = function () {
var storageString = localStorage.getItem(credentials.mobileNumber);
var storageObj = JSON.parse(storageString);

// whats should go here for messageStorage to be equal to storageObj
};

关于 messageStorage.retrieve();变量 messageStorage 必须包含来自 localstorage 的值。

最佳答案

使用 localStorage,数据实际上存储为字符串。然后你使用 JSON.parse 来返回值

JSON.parse() Returns the Object corresponding to the given JSON text.
Example :
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null

但是我看到你想返回变量。那么这个变量的类型是什么?数字、字符串、 bool 值?您可以从 String 转换为您需要的内容

关于javascript - 将本地存储中的对象存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21321284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com