如何从数组中检索值以使用jQuery从其他数组中获取值?

时间:2014-04-15 19:55:31

标签: jquery arrays

我有一些数组:

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"

我错了什么,如何从其他数组中读取值?

2 个答案:

答案 0 :(得分: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 :(得分: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]);
});