2014-04-15 55 views
2

我有幾個數組:如何檢索數組中的值以使用jQuery從其他數組獲取值?

cl = ["Chile", "15", "83"]; 
ar = ["Argentinia", "16.5", "90"]; 
py = ["Paraguay", "19", "81.5"]; 

route = ["cl;ar", "ar;py"]; 

是否可以遍歷一個數組,並從其他陣列獲取的特定值? 我已經試過這沒有工作:

$.each(route, function(index,value) { 
    place = v.split(';'); 
    start = place[0]; 
    end = place[1]; 

    console.log('from '+start[0]+' to '+end[0]); 
}); 

日誌中應顯示:"from Chile to Argentinia", "from Argentinia to Paraguay" 但它把剛"from c to a", "from a to p"

我錯了什麼,我怎麼讀取其他數組的值?

+1

使用eval(end +' [0]') – Matt

+0

謝謝你馬特! eval(...)完美地工作。 – user2402747

回答

3

你可能使用哈希表:

var countries = { 
    cl: {name: 'Chile', prop1: 15, prop2: 83}, 
    ar: {name: 'Argentinia', prop1: 16.5, prop2: 90}, 
    py: {name: 'Paraguay', prop1: 19, prop2: 81.5} 
} 

然後你可以看它當你需要它:

$.each(route, function(index,value) { 
    place = value.split(';'); 
    start = place[0]; 
    end = place[1]; 

    console.log('from '+ countries[start].name + ' to ' + countries[end].name); 
}); 

Fiddle

+1

如果可能的話,我會將問題中的數組中的其他值移動到您的'countries'對象的屬性中...... – ShaneBlake

+0

@ShaneBlake不想組成隨機鍵名稱。好點,但我已經把他們搬進去了。 –

+0

因此,當解決方案難以實現時,我發現我的數據模型設計的很糟糕...... – ShaneBlake

0

嘗試使用哈希表:

var hashtable = {}; 
hashtable['cl'] = ["Chile", "15", "83"]; 
hashtable['ar'] = ["Argentinia", "16.5", "90"]; 
hashtable['py'] = ["Paraguay", "19", "81.5"]; 

route = ["cl;ar", "ar;py"]; 

$.each(route, function(index,value) { 
    var fromTo = value.split(";"); 
    alert('from '+hashtable[fromTo[0]][0]+' to '+hashtable[fromTo[1]][0]); 
});