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

If value == 1 then get the next value in the array

本文关键字:下一个 数组 value 如果 获取      更新时间:2023-09-26
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,则取数组中的下一个值。这里是DK, Danish6000000

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

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);

}

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

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

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];