Andres SK
Andres SK

Reputation: 10982

Finding string-key in Javascript array

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

Answers (4)

Eran Betzalel
Eran Betzalel

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

strager
strager

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

Imran
Imran

Reputation: 91129

Check the type and value of result (and result.detectedSourceLanguage). It could be one of the following

  • result is not defined
  • result is not an object or doesn't have any attribute named detectedSourceLanguage
  • Value of 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

David Andres
David Andres

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

Related Questions