Pregunta

I have read online that the unexpected token u issue can come from using JSON.parse(). On my iPhone 5 there is no problem, but on my Nexus 7 I get this sequence of errors:

enter image description here View large

I realize this is a duplicate, but I am not sure how to solve this for my specific problem. Here is where I implement JSON.parse()

 $scope.fav = []; 

if ($scope.fav !== 'undefined') {
   $scope.fav = JSON.parse(localStorage["fav"]);
}
¿Fue útil?

Solución

Base on your updated question the if condition does not make sense, because you set $scope.fav to [] right before, so it can never be "undefined".

Most likely you want to have your test that way:

if (typeof localStorage["fav"] !== "undefined") {
  $scope.fav = JSON.parse(localStorage["fav"]);
}

As i don't know if there is a situation where localStorage["fav"] could contain the string "undefined" you probably also need test for this.

if (typeof localStorage["fav"] !== "undefined"
    && localStorage["fav"] !== "undefined") {
  $scope.fav = JSON.parse(localStorage["fav"]);
}

Otros consejos

One way to avoid the error (not really fixing it, but at least won't break):

$scope.fav = JSON.parse(localStorage["fav"] || '[]');

You're getting that error because localStorage["fav"] is undefined.

Try this and you'll understand all by yourself:

var a = undefined;
JSON.parse(a);

Unexpected token: u almost always stems from trying to parse a value that is undefined.

You can guard against that like this:

if (localStorage['fav']) {
  $scope.fav = JSON.parse(localStorage['fav'];
}

In my case, the problem was I was getting the value as localStorage.getItem[key] whereas it should have been localStorage.getItem(key).

The rest and normally faced issues have been better explained already by the above answers.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top