简体   繁体   中英

How can I use the string “watch” as a key in a JavaScript associative array?

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

You can do the following:

var dict =
    {
        "watch": 0
    };

alert(dict["watch"]);

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.

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM