簡體   English   中英

遍歷對象中的鍵值

[英]Looping through key values in object

我從本地存儲中獲取了一系列對象:

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

如何獲得所需的輸出?

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

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

這意味着{"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]); 
}

您,我的朋友正在嘗試獲取完整的字符串對象的索引。 它不能那樣工作。 首先,您必須解析它,然后使用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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM