简体   繁体   English

如何在JavaScript关联数组中使用字符串“ watch”作为键?

[英]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 这个表情提醒NaN

alert (dict["watch"]);

I know this is because watch() is a function that is part of the object prototype. 我知道这是因为watch()是对象原型一部分的函数。 Is there anyway around this so I can use any word as a key in my array? 无论如何,我可以在数组中使用任何单词作为键吗?

I am using Firefox 3.6.6 我正在使用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. * 从技术上讲,javascript没有“关联数组”,而具有“对象”-但对于此特定目的,它们以有效的相同方式工作。

I found the root of the problem (of course it was 5 seconds after I asked my question): 我找到了问题的根源(当然是在我问了问题之后5秒钟):

My code checks that the key in dict is undefined or null before assigning a value like this: 我的代码在分配这样的值之前检查dict中的键是否未定义或为null:

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

But since "watch" is part of the object prototype, dict[key] == null would never be true. 但是,由于“监视”是对象原型的一部分,因此dict[key] == null永远不会为真。

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 现在是function watch(){ native code }或类似的功能

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 = {} . 尝试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. 在Firefox 3.3.6,Chrome 5.0.375.99 beta,IE 8和Safari 5中,它为我警报0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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