0

I have a basic question regard to Javascript.

as Javascript do not have hash table objects, but I realize that I can just build a object to use it as a hash table like the following:

var hashtable = {
    Today : {"I", "feel", "good"},
    Tomorrow : {'is', 'another', 'day'},
    Yesterday : 'alwaysGood'
}

I have search a lot on the Internet, there are some means which using associativeArray or which build its own object as a hash table, is the above native object building method not good?

Haven
  • 7,808
  • 5
  • 25
  • 37
  • 1
    Well you cannot do exactly what you've posted, as it's syntactically incorrect. However the basic idea of using an object like a hash table is fine. – Pointy May 13 '14 at 15:11
  • ^^ What he said, the idea is fine, but your code is invalid, and there are no associative arrays in javascript. – adeneo May 13 '14 at 15:14
  • @adeneo Objects *are* [associative arrays](http://en.wikipedia.org/wiki/Associative_array) – Andrew Vermie May 13 '14 at 15:21
  • 2
    @AndrewVermie Technically, no, they're not -- but they can be used like associative arrays in other languages are used. – Blazemonger May 13 '14 at 15:41
  • possible duplicate of [What's the difference between objects and associated array in javascript?](http://stackoverflow.com/questions/8146104/whats-the-difference-between-objects-and-associated-array-in-javascript) – zmo May 13 '14 at 15:48

1 Answers1

2

Your code sample is not valid JavaScript because of this {"I", "feel", "good"}. In this context, the curly braces represent an object literal, and each of the object's properties must be assigned a value.

A valid version would look like:

var hashtable = {
    Today : ["I", "feel", "good"],
    Tomorrow : ['is', 'another', 'day'],
    Yesterday : 'alwaysGood'
}

Note the use of [] which creates an array. Arrays in JavaScript are numerically keyed, there is no concept of an associative array like there is in other languages. However, a JavaScript array itself, is also an object, so you can freely add properties:

var arr = [];
arr.Today = 'some value';

To avoid the use of an array in your example, you would need to set values for all properties:

var hashtable = {
    Today : {"I" : "i val", "feel" : "feel val", "good" : "good val"},
    Tomorrow : {'is' : 'is val', 'another' : 'another val', 'day' : 'day val'},
    Yesterday : 'alwaysGood'
}

Using objects in this way is valid and acceptable. For more information refer to Working With Objects (MDN).

MrCode
  • 63,975
  • 10
  • 90
  • 112