我有一个像这样的对象:
var routes = {
'fr-FR': [
'/accueil',
'/offre',
'/specifications'
],
'en-US': [
'/home',
'/offer',
'/specifications-en'
],
'de-DE': [
'/startseite',
'/annbod',
'/specificaties'
]
};
我的目标是根据网址获取区域设置。
我尝试过类似:(url = /offer
)
var getLocale = function(url) {
console.log('getLocale for %s', url);
for(var language in routes) {
for(var route in language) {
console.log('lg = ' + language);
console.log('rt = ' + route);
if (route === url) {
return route;
}
}
}
};
我得到的输出是:
getLocale for /offer
lg = fr-FR
rt = 0
lg = fr-FR
rt = 1
lg = fr-FR
rt = 2
lg = fr-FR
rt = 3
lg = fr-FR
rt = 4
lg = en-US
rt = 0
lg = en-US
rt = 1
lg = en-US
rt = 2
lg = en-US
rt = 3
lg = en-US
rt = 4
lg = de-DE
rt = 0
lg = de-DE
rt = 1
lg = de-DE
rt = 2
lg = de-DE
rt = 3
lg = de-DE
rt = 4
所以我想我在第一个for-in循环中做得很好,但我不知道如何在数组中循环而不是其名称的字符...
另外,我在很多SO帖子上看到,for-in循环不是在某些情况下循环的最佳方式,而是哪些?
提前致谢。
答案 0 :(得分:7)
循环的第一部分是正确的但请注意:language
是一个字符串(" fr-FR"," en-US"等)不是您正在寻找的阵列。
相反,您可以通过访问routes[language]
来访问路线:
for (var language in routes) {
var routeByLanguage = routes[language];
for (var i = 0, len = routeByLanguage.length; i < len; i++) {
console.log('lg = ' + language);
console.log('rt = ' + routeByLanguage[i]);
if (routeByLanguage[i] === url) {
return routeByLanguage[i];
}
}
}
至于何时使用for-in循环,当你想要访问它们的键时,你可以*在对象上使用它们(就像你在routes
对象上一样)。你不应该将它们用于数组。
*如果您使用Object.keys
获取密钥,则不必使用它们。
答案 1 :(得分:1)
Javascript迭代器通常比循环更具表现力:
var routes = {
'fr-FR': [
'/accueil',
'/offre',
'/specifications'
],
'en-US': [
'/home',
'/offer',
'/specifications-en'
],
'de-DE': [
'/startseite',
'/annbod',
'/specificaties'
]
};
url = '/annbod'; // did you mean "angebot"?
locale = Object.keys(routes).filter(function(locale) {
return routes[locale].indexOf(url) >= 0;
});
console.log(locale)[0]; // 'de-DE'