Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associative array with alphabets as keys in JavaScript

Tags:

javascript

I am looking to create a JavaScript object (associative array) with alphabets as keys. What is the best way to accomplish this?

Example -

obj[a] = 'somevalue'
obj[b] = 'somevalue' 
...
obj[z]= 'some value'

Assigning alphabets as keys dynamically.

like image 218
thinking_hydrogen Avatar asked May 16 '12 10:05

thinking_hydrogen


People also ask

How do you write associative array in JavaScript?

An associative array is declared or dynamically createdWe can create it by assigning a literal to a variable. var arr = { "one": 1, "two": 2, "three": 3 }; Unlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object.

Does JavaScript support associative array?

JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.

Is a JavaScript object an associative array?

While it is clear that arrays are JavaScript objects, JavaScript also allows objects and their properties to be accessed as if they were arrays. Normal JavaScript arrays index their values in order using integer indices.


1 Answers

Here's a quick and lazy way to create the object:

var a = 97;
var charArray = {};
for (var i = 0; i<26; i++)
    charArray[String.fromCharCode(a + i)] = String.fromCharCode(a + i);

console.log(charArray);

http://jsfiddle.net/V2B7S/

like image 175
Thach Mai Avatar answered Sep 20 '22 20:09

Thach Mai