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];
2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I mean create those variables automatically.
@RyanYiada: what do you mean by "automatically"? You mean a for loop or something like that?
@RyanYiada You might be able to do it with eval. But why? There's probably something wrong with your design if you need to do this. You can access object properties by name with list[name].
@Barmar thank you.I just want to know this way is illegal.
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.

Comments

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

2 Comments

Is this last line valid?
Sry, was thinking 'bout an array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.