LocalStorage Get Item with Dot/Bracket Notation Not Working with JSON.parse()

拟墨画扇 提交于 2019-12-11 07:52:12

问题


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)



来源:https://stackoverflow.com/questions/12623951/localstorage-get-item-with-dot-bracket-notation-not-working-with-json-parse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!