Reputation: 10982
1) I have this Javascript array:
lang=new Array();
lang["sq"]="Albanian";
lang["ar"]="Arabic";
lang["en"]="English";
lang["ro"]="Romanian";
lang["ru"]="Russian";
2) In some other process, there is a returned value in a variable:
result.detectedSourceLanguage = 'en';
3) Now, i want to print the language full name by doing this:
alert(lang[result.detectedSourceLanguage]);
The dialog displays: undefined
Any ideas?
BTW: im using JQuery, so JQuery solutions are welcomed.
Upvotes: 8
Views: 21040
Reputation: 4203
This script generates a message box (checked in IE & FF) that says "English":
lang = new Array();
lang["sq"] = "Albanian";
lang["ar"] = "Arabic";
lang["en"] = "English";
lang["ro"] = "Romanian";
lang["ru"] = "Russian";
detectedSourceLanguage = 'en';
alert(lang[detectedSourceLanguage]);
The only problem could be the result
object.
Upvotes: 3
Reputation: 90062
An Array
uses integer indexes. You probably want an Object
, which supports string indexes:
lang=new Object();
lang["sq"]="Albanian";
lang["ar"]="Arabic";
lang["en"]="English";
lang["ro"]="Romanian";
lang["ru"]="Russian";
// or
lang = {
'sq': 'Albanian',
'ar': 'Arabic',
// ...
'ru': 'Russian'
};
(The latter example is probably better as more JS programmers would be happy with it.)
Upvotes: 21
Reputation: 91129
Check the type and value of result
(and result.detectedSourceLanguage
). It could be one of the following
result
is not definedresult
is not an object or doesn't have any attribute named detectedSourceLanguage
result.detectedSourceLanguage
is not a string or there's no such key in lang
(then it's supposed to return undefined
for alert(lang[result.detectedSourceLanguage]);
)BTW, your problem has nothing to do with jQuery
Upvotes: 1
Reputation: 31811
Try alerting result.detectedSourceLanguage immediately prior to its use. There is a chance that it doesn't equal what you expect it to. This should work.
Upvotes: 0