问题描述
如果可能,我希望能够使用速记符号从localStorage
获取项目,然后在其上使用JSON.parse()
.
If possible, I would like to be able to use shorthand notation to get an item from localStorage
and then use JSON.parse()
on it.
在下面的代码中,如果我使用以下代码,它将起作用:
In my code below, if I use the following it works:
var retrievedObject = JSON.parse(localStorage.getItem('testObject')); //works
但是,如果我使用以下两个速记选项之一,则它不起作用:
However, if I use one of the two following shorthand options, it doesn't work:
var retrievedObject = JSON.parse(localStorage.testObject); //doesn't work
var retrievedObject = JSON.parse(localStorage['testObject']); //doesn't work
我所有的代码都在jsFiddle下方和上: http://jsfiddle.net/TestB/1/.
All of my code is below and on jsFiddle: http://jsfiddle.net/TestB/1/.
//var retrievedObject = JSON.parse(localStorage.getItem('testObject')); //works
var retrievedObject = JSON.parse(localStorage.testObject); //doesn't work
//var retrievedObject = JSON.parse(localStorage['testObject']); //doesn't work
if (retrievedObject == null) {
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.testObject = JSON.stringify(testObject);
}
else {
retrievedObject.four = 4;
// Put the object into storage
localStorage.testObject = JSON.stringify(retrievedObject);
}
// Retrieve the object from storage
var retrievedObject = JSON.parse(localStorage.getItem('testObject'));
console.log('retrievedObject: ', retrievedObject);
推荐答案
第一次未定义localStorage.testObject
时会发生此问题.
The problem occurs the first time, when the localStorage.testObject
is not yet defined..
在这种情况下,localStorage.testObject
是未定义的,而JSON.parse
失败并带有该参数
In that case localStorage.testObject
is undefined and JSON.parse
fails with that argument
另一方面,getItem
方法在内部进行处理并返回null
.
On the other hand the getItem
method handles this internally and returns null
..
您可以使用JSON.parse(localStorage.testObject || null)
这篇关于带有点/括号符号的LocalStorage获取项目不适用于JSON.parse()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!