如何从给定字符串中获取JavaScript对象?
如何从字符串中获取对象 我编写了一个localStorage util,其中有如何从给定字符串中获取JavaScript对象?,javascript,Javascript,如何从字符串中获取对象 我编写了一个localStorage util,其中有get和set方法 在set方法中: function fnGet(name){ var getVal=storage.getItem(name); if(getVal==null){ return console.log('the localstorage did\'t have'+name); } if((getVal.split(':-:')).lenght>1){ return eval('('
get
和set
方法
在set方法中:
function fnGet(name){
var getVal=storage.getItem(name);
if(getVal==null){
return console.log('the localstorage did\'t have'+name);
}
if((getVal.split(':-:')).lenght>1){
return eval('('+getVal.split(':-:')[0]+')');
}
return getVal.split(':-:')[0];
}
您可以忽略:-:
,它是保存的数据和时间戳的分隔符
如果数据存储在JavaScript对象中,则会出现如下问题:
'{“pk”:1,“用户名”:“test01”,“电子邮件”:“名字”:“姓氏”:“}:-:1521381469910”
当我使用get方法时,它会变成这样:
'{“pk”:1,“用户名”:“test01”,“电子邮件”:““名字”:““姓氏”:“}”
如何访问JavaScript对象
如何优化我的get方法?
JSON.parse
对存储区的响应进行分析。localStorage将所有内容存储为字符串,因此您首先需要对对象进行字符串化,就像我假设的那样,否则您将无法将其保存到存储中
然后,要检索它,您需要解析它以再次获取javascript对象。LocalStorage保存字符串化的数据。因此,您应该使用
JSON.parse(yourVariable)
将数据作为JSON返回
function fnGet(name) {
var getVal = storage.getItem(name);
if (getVal == null) {
return console.log('the localstorage did\'t have' + name);
}
if ((getVal.split(':-:')).lenght > 1) {
return eval('(' + JSON.parse(getVal.split(':-:')[0]) + ')');
}
return getVal.split(':-:')[0];
}
您所需要的只是JSON.parse,它将字符串作为参数,如果它是有效的对象字符串,则返回一个对象,否则将抛出一个错误两件事:
JSON.parse()
而不是eval
;这不仅更安全,而且更能说明你的意图。注意:这需要对保存在localStorage中的数据使用JSON.stringify()
length
拼写为“lenght”函数fnGet(名称){
让getVal=storage.getItem(名称)
if(getVal==null){
return console.log(`localstorage没有:${name}`);
}
让val=getVal.split(“:-:”);//对于性能缓存,将拆分
如果(val.length>1){//拼写错误:“length”->length
返回JSON.parse(val[0]);
}
返回值[0];
}
在两种情况下,如果数据是类似“aaaaa”的字符串,则不能使用JSON.parse@244boy在保存/设置函数中,JSON.stringify数据,而'aaaaaaa'
将是'aaaaaaa'
,可以直接解析,如果保存对象时JSON.stringify()
,则始终可以解析,但您的问题指出,如果保存一个javascript对象,'aaaa'
不是一个对象,而是一个字符串。“localStorage将所有内容存储为JSON”-否。localStorage仅存储字符串。在这些字符串中使用JSON的程序,而不是使用<代码>:-//Case>作为分隔符,考虑将数据再次包装在元数据的另一个对象中,并从本地存储中对整个事物进行纵横化/解析。