开发者

Why does my hash table contain a spurious value?

开发者 https://www.devze.com 2023-04-02 02:17 出处:网络
I\'m creating a hash table to check whether a four-letter word is valid: function myClickHandler(myClickHandler)

I'm creating a hash table to check whether a four-letter word is valid:

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'];
}

However, when I examine the hash table in a debugger the first element seems to be:

wordhash['10'] = true

so the final statement in m开发者_如何学运维y test function sets the variable text to true. Why is this happening?

Thanks


You're doing a few things not completely correct:

  • Don't use for in for an array.
  • With key/value pairs, use an object, not an array.
  • Use [] to make arrays, {} for objects.
  • A for loop does not need a trailing ;.

You could change it into:

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);

What I then get logged is what I think you expect it to be:

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


Iterating over an array like this is not a good practice, try checking the value of i in the loop. It will give lots of unwanted data.

You better use i as an index by making the loop like this:

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

In this case when querying wordhash['10'] it will give undefined and when querying anything from the first array like abed it will give true.

0

精彩评论

暂无评论...
验证码 换一张
取 消