几天前我遇到了这个问题,令人惊讶的是,这为我的逻辑思维带来了很多问题。
我们有三个简单的数组:
var countries = [1, "DK", 2, "USA", 3, "Sweden"];
var languages = [2, "English", 1, "Danish", 3, "Swedish"];
var population = [3, 8000000, 1, 6000000, 2, 3000000000];
在控制台日志中,输出应如下所示:
// In USA people speak English and there live 300000000 people
// In DK people speak Danish and there live 6000000 people
// In Sweden people speak Swedish and there live 8000000 people
现在,有人告诉我可以使用for循环来解决它,但是我对如何获取数字的位置然后保存这些数字感到困惑,因此可以从其他两个数组中选择它们。
它必须是动态的,因此,仿佛我向数组中添加了更多元素一样,它会自动生成类似于我上面提到的三个句子。
这是我从老师那里得到的,因此输入数组必须保持这样。每个数字后面都有一个按升序排列的字符串,这是我们必须弄清楚的模式,因此它看起来像我上面评论的文本。
您肯定需要使用多个for循环。
除非您想更改数据的结构(请参见georg的回答),否则类似的事情应该起作用:
for (var i = 0; i < countries.length; i+=2) {
var countryId = countries[i];
var countryName = countries[i+1];
var countryLanguage, countryPopulation;
for (var j = 0; j < languages.length; j+=2) {
if (languages[j] == countryId) countryLanguage = languages[j+1];
}
for (var j = 0; j < population.length; j+=2) {
if (population[j] == countryId) countryPopulation = population[j+1];
}
console.log("In " + countryName + " people speak " +
countryLanguage + " and there live " +
countryPopulation + " people");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句