如果value == 1则获取数组中的下一个值

时间:2015-08-30 16:18:19

标签: javascript arrays

var countries = [1,"DK",2,"USA",3,"Sweden",];
var languages = [2,"EN",3,"Swedish",1,"Danish"];
var population = [2,"300000000",1,"6000000",3,"8000000"];

在javascript中,有没有办法在数组中查找值,例如,如果值为1,则获取数组中的下一个值。这里是DKDanish6000000

我有这个,但认为它应该是更简单的方法

for(var i = 1 ; i < countries.length; i = i+2){
var countryName = countries[i];
var countryId =  countries[i-1];
for(var j = 0; j < languages.length; j = j+2){
    if(languages[j] == countryId){
        var positionSpokenLanguage = j + 1;
        var spokenLanguage = languages[positionSpokenLanguage];
    }
    if(population[j] == countryId){
        var positionPopulation = j + 1;
        var totalPopulation = population[positionPopulation];
    }
}
var message = "In "+countryName+" people speak "+spokenLanguage+
                            " and there are "+totalPopulation+" inhabitatns";

console.log(message);

}

1 个答案:

答案 0 :(得分:1)

由于您实际上在数组中的每个其他项目中寻找值,因此没有内置方法。

如果您知道该值在数组中,您可以循环直到找到它:

var index = 0;
while (countries[index] != 1) index += 2;
var value = countries[index + 1];

您的数据格式不直观,这使得使用起来有点尴尬。如果可能,您应该使用数据格式,不要将键与值混合,例如对象:

var countries = { 1: "DK", 2: "USA", 3: "Sweden" };

然后你可以使用密钥获取值:

var value = countries[1];