tags:

views:

48

answers:

5

I have an array declared like this:

var dict = [];

When I do this:

dict["watch"] = 0;

this expression alerts NaN

alert (dict["watch"]);

I know this is because watch() is a function that is part of the object prototype. Is there anyway around this so I can use any word as a key in my array?

I am using Firefox 3.6.6

+1  A: 

You can do the following:

var dict =
    {
        "watch": 0
    };

alert(dict["watch"]);
BrunoLM
Marking yours as the right answer because you suggested something that worked sooner than the other answers
SimpleCoder
+1  A: 

Shorthand for associative arrays* is curly-braces, rather than square ones:

var dict={};
dict["watch"] = 0;

Or simply:

var dict={ watch:0 };

*Technically javascript doesn't have "associative arrays", it has "objects" - but they work in effectively the same way for this specific purpose.

lucideer
+1  A: 

I found the root of the problem (of course it was 5 seconds after I asked my question):

My code checks that the key in dict is undefined or null before assigning a value like this:

 if (dict[key] == null)
      dict[key] = 0;

But since "watch" is part of the object prototype, dict[key] == null would never be true.

Edit:

However, even when I do this:

if (typeof dict[word] == "function" || dict[word] == null)
    dict[word] = 0;

the value of

dict["watch"]

is now function watch(){ native code } or something like that

Got it:

In my infinite wisdom, I had a similar mistake somewhere else in my code which I have now fixed. Thanks for everyone's help!

SimpleCoder
+1  A: 

Try dict = {}. [] is for array literals, {} is for object literals, which are, more or less, hashes. It gets confusing, since you still use square brackets for indexing.

Weston C
+1  A: 

Where are you executing your code? In Firefox 3.3.6, Chrome 5.0.375.99 beta, IE 8, and Safari 5, it alerts 0 for me.

Samuel Meacham
I am using Firefox 3.6.6
SimpleCoder