为什么我的哈希表包含虚假值?

joh*_*ies 0 javascript

我正在创建一个哈希表来检查一个四个字母的单词是否有效:

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'];
}
Run Code Online (Sandbox Code Playgroud)

但是,当我在调试器中检查哈希表时,第一个元素似乎是:

wordhash['10'] = true
Run Code Online (Sandbox Code Playgroud)

所以我的测试函数中的最后一个语句将变量text设置为true.为什么会这样?

谢谢

pim*_*vdb 5

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

  • 不要for in用于数组.
  • 使用键/值对,使用a object而不是a array.
  • 使用[]使阵列{}的对象.
  • 一个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);
Run Code Online (Sandbox Code Playgroud)

然后我记录的是我认为你期望它:

Object
  abed: true
  abet: true
  able: true
  ably: true
  abut: true
  aces: true
  ache: true
  achy: true
Run Code Online (Sandbox Code Playgroud)