LocalStorage Get Item with Dot/Bracket Notation No

2019-07-25 16:20发布

问题:

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

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);​

回答1:

The problem occurs the first time, when the localStorage.testObject is not yet defined..

In that case localStorage.testObject is undefined and JSON.parse fails with that argument

On the other hand the getItem method handles this internally and returns null..

You could use JSON.parse(localStorage.testObject || null)