1

Let's think about this:

var list = [a1:"123",b2:"234",c3:"345"];

This list obj can create variables by key name like this?

var a1 = list[0];   
var b2 = list[1];  
var c3 = list[2];
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Ryan Yiada
  • 4,739
  • 4
  • 18
  • 20
  • Indent a line with 4 spaces to get code to render as code blocks -- quotes (`>`) are meant for text from elsewhere or a quote from someone else. – Qantas 94 Heavy Feb 22 '14 at 09:34
  • and [Is there an easy way to create dynamic variables with Javascript?](http://stackoverflow.com/q/2413414/218196) – Felix Kling Feb 22 '14 at 10:25

3 Answers3

3

When you use [] notation, you can only create arrays with numeric indexes. To have named properties, you must use {} object notation:

var list = { a1: "123", b2: "234", c3: "345" };

You can then access them as list.a1, list.b2, and list.c3.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

The question is not clear. What you show in the example is valid. But you could also create variable names like you suggest like

for( var key in list ) {
  window[key] = list[key];
} 

This way you will end up having a1, b2 and c3 variables with the desired value, however, these will be globals.

marekful
  • 14,986
  • 6
  • 37
  • 59
0

First of all you have a mistake, you are trying to merge hash array and regular array. You should either announce an array like this:

var list = ['123', '234', '345'] 

and then

var a1 = list[0] 

and so on, or announce it like hash array and it will look like this

var list = {'a':'123','b':'234','c':'345'}
var a1 = list.a
Y.Puzyrenko
  • 2,166
  • 1
  • 15
  • 23