[英]Unexpected token: u JSON.parse() issue
I have read online that the unexpected token u issue can come from using JSON.parse(). 我在网上看到,意外的令牌问题可能来自于使用JSON.parse()。 On my iPhone 5 there is no problem, but on my Nexus 7 I get this sequence of errors:
在我的iPhone 5上没有问题,但在我的Nexus 7上,我得到了一系列错误:
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()
这是我实现JSON.parse()的地方
$scope.fav = [];
if ($scope.fav !== 'undefined') {
$scope.fav = JSON.parse(localStorage["fav"]);
}
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"
. 根据您更新的问题,
if
条件没有意义,因为您之前将$scope.fav
设置$scope.fav
[]
,因此它永远不会是"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. 由于我不知道是否存在
localStorage["fav"]
可能包含字符串"undefined"
您可能还需要对此进行测试。
if (typeof localStorage["fav"] !== "undefined"
&& localStorage["fav"] !== "undefined") {
$scope.fav = JSON.parse(localStorage["fav"]);
}
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
. 您收到该错误是因为
localStorage["fav"]
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
. Unexpected token: u
几乎总是源于尝试解析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)
. 在我的情况下,问题是我得到的值是
localStorage.getItem[key]
而它应该是localStorage.getItem(key)
。
The rest and normally faced issues have been better explained already by the above answers. 通过上述答案已经更好地解释了其余的和通常面临的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.