Ruby_Pinky_Ring
Ruby_Pinky_Ring

Reputation: 3

Why is my JavaScript hash with the reserved word "toString" as a key showing NaN?

I am doing a programming exercise that wants me to count all the occurrences of a word within a string, like "the dog went to the other dog".

I have to return a hash with the counts like so for the example above: {the: 2, dog: 2, went: 1, to: 1, other: 1}

But my question is how do I deal with counting reserved words, I am getting NaN.

So this string {"the dog went to the other dog toString"}, returns this for me:

{the: 2, dog: 2, went: 1, to: 1, other: 1, toString: NaN}

How can I get this to give me the real count and not NaN.

Upvotes: 0

Views: 159

Answers (1)

Glen
Glen

Reputation: 144

JavaScript actually does not have hashes. So if you are creating a hash like this: hash = {} then you are actually creating an object with already existing properties in its prototype chain. This includes the toString function. To avoid this, create an object with Object.create(null) to store your word counts.

Here is an example:

 var words = function(string) { 
 var words_array = string.split(" "); 
 var word_count_hash = Object.create(null); 

 words_array.map( function (word){
   if (word in word_count_hash)
     word_count_hash[word] ++; 
   else word_count_hash[word] = 1;
  }); 

  return word_count_hash;
  }

Upvotes: 5

Related Questions