Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我如何使用字符串“quot;手表;作为JavaScript关联数组中的键?_Javascript - Fatal编程技术网

我如何使用字符串“quot;手表;作为JavaScript关联数组中的键?

我如何使用字符串“quot;手表;作为JavaScript关联数组中的键?,javascript,Javascript,我有一个数组声明如下: var dict = []; if (dict[key] == null) dict[key] = 0; 当我这样做时: dict["watch"] = 0; if (typeof dict[word] == "function" || dict[word] == null) dict[word] = 0; 此表达式提醒NaN alert (dict["watch"]); 我知道这是因为watch()是对象原型的一部分。是否存在这样的情况,

我有一个数组声明如下:

var dict = [];
 if (dict[key] == null)
      dict[key] = 0;
当我这样做时:

dict["watch"] = 0;
if (typeof dict[word] == "function" || dict[word] == null)
    dict[word] = 0;
此表达式提醒
NaN

alert (dict["watch"]);
我知道这是因为
watch()
是对象原型的一部分。是否存在这样的情况,以便我可以在数组中使用任何单词作为键


我使用的是Firefox 3.6.6,您可以执行以下操作:

var dict =
    {
        "watch": 0
    };

alert(dict["watch"]);

关联数组的缩写是大括号,而不是方括号:

var dict={};
dict["watch"] = 0;
或者简单地说:

var dict={ watch:0 };

*从技术上讲,javascript没有“关联数组”,它有“对象”-但它们的工作方式与此特定用途的工作方式相同。

我找到了问题的根源(当然是在我提出问题后5秒):

我的代码在分配如下值之前检查
dict
中的键是否未定义或为空:

var dict = [];
 if (dict[key] == null)
      dict[key] = 0;
但由于“watch”是对象原型的一部分,
dict[key]==null
永远不会为真

编辑:

然而,即使我这样做:

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

dict["watch"]
现在是
函数watch(){native code}
或类似的东西

明白了:


在我无限的智慧中,我在代码的其他地方也犯了类似的错误,现在我已经修复了。谢谢大家的帮助

试试
dict={}
<代码>[]用于数组文本,
{}
用于对象文本,它们或多或少都是散列。这会让人困惑,因为您仍然使用方括号来编制索引

您在哪里执行代码?在Firefox 3.3.6、Chrome 5.0.375.99 beta版、IE 8和Safari 5中,它会为我提醒0。

如果你在Firefox上,这是唯一一个有
对象的浏览器。watch
,那么为什么你会在提醒中看到
NaN
而不是
watch
功能?我也是Firefox 3.6.6,我看到了
function watch(){[native code]}
。问题是在我的代码中的某个地方,我没有检查
dict[“watch”]
是否是一个函数。我的代码所做的一件事是:
dict[“watch”]++
,所以它试图增加一个函数。感谢Anurag-我不知道这个方法。便于将来参考。我假设它是不可数的?@lucideer-添加到
对象中的任何东西。prototype
必须是不可数的,否则它会在
for..in
循环中显示,除非它是应用程序无法缺少的:)。这是一种非常方便的方法,可以监控对象的更改,而无需经常轮询对象,我希望所有浏览器都能将此添加到他们的产品库中。@SimpleCoder-这就是为什么
NaN
:)将您的答案标记为正确答案的原因,因为您建议的答案比其他答案更快