2011-09-04 114 views
0

我创建一个哈希表来检查四个字母的单词是否有效:为什么我的散列表包含虚假值?

function myClickHandler(myClickHandler) 
{ 
    var words4=new Array("abed", "abet", "able", "ably", "abut", "aces", "ache", "achy"); 

    // Initialise hash table 
    var wordhash = new Array(); 

    for (var i in words4) 
     { 
      wordhash[ words4[i] ] = true; 
     }; 

    var text = wordhash['10']; 
} 

然而,当我检查哈希表在调试器的第一个元素似乎是:

wordhash['10'] = true 

所以我的测试函数中的最后一个语句将变量文本设置为true。这是为什么发生?

感谢

回答

5

你正在做的一些事情不能完全正确:

  • 不要对数组使用for in
  • 使用键/值对,请使用object而不是array
  • 使用[]为对象创建数组{}
  • A for循环不需要尾随;

您可以将其更改为:

var words4 = ["abed", "abet", "able", "ably", "abut", "aces", "ache", "achy"]; 

// Initialise hash table 
var wordhash = {}; 

for (var i = 0; i < words4.length; i++) { 
    wordhash[ words4[i] ] = true; 
} 

console.log(wordhash); 

我则得到记录是什么,我认为你希望它是:

Object 
    abed: true 
    abet: true 
    able: true 
    ably: true 
    abut: true 
    aces: true 
    ache: true 
    achy: true 
+0

谢谢 - 在你的帮助下,我的程序正在运行;请参阅: http://www.plasticki.com/show?9EE。 我欢迎任何改进建议。 David – johnsondavies

+0

@johnsondavies:你的代码确实很有趣。但是,我不会建议与'未定义'进行比较。看:'undefined = 1; var a;一个== undefined'会产生'false',因为undefined不是真的* undefined。相反,使用'typeof something =='undefined''。一些常见的做法是使用'==='而不是'=='和'[]'来代替'new Array()'。 – pimvdb

3

遍历数组这样是不是好的做法,请尝试检查循环中的i的值。它会提供大量不需要的数据。

你最好通过使循环这样的使用i作为索引:

for (var i=0; i<words4.length; i++){ 
    wordhash[words4[i]] = true; 
} 

在这种情况下查询wordhash['10']时,它会给undefined,并从第一阵列状abed查询什么时候会给true