Question

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?

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top