views:

378

answers:

4

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.

A: 

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.

David Andres
actually that alert displays: en
andufo
what browser are you running this against?
David Andres
+1  A: 

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

Imran
that has nothing to do with the prob. if i call:alert(lang['en']);it prints English as it should.
andufo
+5  A: 

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

strager
Just a note on why the OP sometimes worked: In JS Arrays are objects, so you can attach arbitrary properties to them as you can with any other object. As was found though, these additional properties can get lost if the array is serialized to its normal `['val 1', 'val 2', 'val 3, ...]` syntax. Its likely that somewhere in JQuery or elsewhere a serialization/deserialization is happening to the array, and the additional properties are lost.
Adam Franco
I know an `Array` is an `Object`, but really, you should treat it as a sequential array (like `std::vector` in C++'s STL) and not an associative array (like `std::map` in C++'s STL or PHP-like arrays), to avoid confusion. Serialization/conversion may be the problem as you suggest, Adam.
strager
+1  A: 

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.

Eran Betzalel
i addedalert(lang[String(detectedSourceLanguage)]);that worked out. thanks!
andufo