Why can't we declare arrays with string index in Javascript? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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.

21st Jun 2017, 7:20 PM
Sourav Raha
Sourav Raha - avatar
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.
21st Jun 2017, 7:59 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Well the pseudo dictionary was a good implementation of the feature. Thanks ChaoticDawg
21st Jun 2017, 8:14 PM
Sourav Raha
Sourav Raha - avatar