0
Why can't we declare arrays with string index in Javascript?
I'm learning JavaScript and i want to know why in JS an array arr["str"] is taken as an object rather than a array with string index.
2 Answers
+ 1
You can create a pseudo dictionary using JavaScript object notation:
Initialization:
var dict = new Object(); // creates an empty object
var dict = {}; // short hand for above
// or initialize with keys and values
var dict = {
"first": "tom",
"second": "jerry",
"third": "mickey",
"fourth": "pluto"
}
assign key, value to dict or change value of current key:
dict["fourth"] = "daffy"; // changes fourth to daffy
dict["fifth"] = "donald"; // adds fifth with value of donald
access value with key:
var name = dict["first"]; //name = tom
loop over keys in dict and get values:
for(var key in dict) {
alert(dict[key]);
}
JavaScript doesn't have a dictionary type, but this is about as close as it gets.
+ 1
Well the pseudo dictionary was a good implementation of the feature. Thanks ChaoticDawg