2

我从本地存储中获取一组对象:

saved_selection = window.localStorage.getItem('match_selection');

console.log('saved selection obj is ');
console.log(saved_selection);

输出是:

{"236":"Forward_2","243":"Forward_1"} 

现在我想循环并获取键和值。所以我这样做:

for(var index in saved_selection) {
    console.log(index + " -> " + saved_selection[index]); 
}

但我得到:

0 -> { 
1 -> " 
2 -> 2 
3 -> 3 

等,而不是:

236 -> Forward_2
243 -> Forward_1

如何获得所需的输出?

4

3 回答 3

2

你想解析出 localStorage 返回的字符串:

saved_selection = JSON.parse( window.localStorage.getItem('match_selection') );
于 2013-09-18T14:15:49.790 回答
1

这意味着它{"236":"Forward_2","243":"Forward_1"}String的实例,而不是Object
为了

var v1 = '{"236":"Forward_2","243":"Forward_1"}';

这行不通,但是对于

var v2 = {"236":"Forward_2","243":"Forward_1"};  

您应该使用JSON.parse方法 转换String为。Object

saved_selection = JSON.parse(saved_selection);
for(var index in saved_selection) {
    console.log(index + " -> " + saved_selection[index]); 
}
于 2013-09-18T14:15:41.397 回答
1

您,我的朋友正在尝试获取完整字符串化对象的索引。它不是那样工作的。首先,您必须解析它并使用JSON.parse().

往下看 :

JS:

var saved_selection = JSON.parse('{"236":"Forward_2","243":"Forward_1"}') ;

var saved_selection1 = '{"236":"Forward_2","243":"Forward_1"}' ;

for(var index in saved_selection) {
    console.log(index + " -> " + saved_selection[index]); 
}
for(var index in saved_selection1) {
    console.log(index + " -> " + saved_selection1[index]); 
}

第一个 for 循环返回所需的 O/P,但第二个不返回。

在这里找到工作小提琴:http: //jsfiddle.net/eMVNk/2/

于 2013-09-18T14:20:30.270 回答