0

I get an array like this:

 var array = [ [ [1,1],[1,2],[1,3] ] , [ [2,2],[3,3],[4,4] ]  ] ;

I want to seperate the array in two normal arrays and put the content in incrementing independently variables (data1, data2, data3, data4).

But the var array is different in size at different time (sometimes 3 arrays, sometimes 4, ... ) Now my problem is how to create the incrementing independently variables data1, data2, ...

I thought of this

counter = 0;
for (var content in array)
{
   data + counter.toString() = content;
   content++;
}

But that doesn't work (By the way I did not expect it :D )

Can we find a solution together?

Best regards, Susan!!

Susanne92
  • 217
  • 1
  • 6
  • 21
  • why would you do that ? you could create a global var `window["data"+counter]` – Moritz Roessler May 29 '13 at 10:09
  • 1
    As a technical "Does JS allow such a thing?" question this is reasonable, but for practical purposes why would you want to do it? In a code review it would be pointed out that independent incrementing variable names is something that should be replaced with an array, _especially_ when you have a variable number of values like you say you do - why would you want to go the other way? – nnnnnn May 29 '13 at 10:23

3 Answers3

1

The only way to create variables (i.e. properties of the local execution context) is to declare them using var in a variable declaration, which does not allow for expressions.

It is a bit of a quirk of javascript that global variables are made properties of the global object, but that is the only execution context where you can use an expression to create what is effectively a variable, e.g.

var globalObject = this;
globalObject.foo = 'foo';
globalObject[foo + 'bar'] = 'foobar';

in the global scope is, in many respects (but not exactly), equivalent to:

var foo = 'foo';
var foobar = 'foobar';

However, you can't get a reference to local execution or variable objects in a function context so you can't create local variables that way.

Far better to create the "variables" as properties of an object.

RobG
  • 142,382
  • 31
  • 172
  • 209
1
var array = [ [ [1,1],[1,2],[1,3] ] , [ [2,2],[3,3],[4,4] ]  ] ;

for (var i=1;i<=array.length;i++)
   window["data" + i] = array[i-1].slice();

Fiddle:http://jsfiddle.net/xC2kT/

I would recommend you to use for for arrays and for..in for Javascript objects

Prasath K
  • 4,950
  • 7
  • 23
  • 35
0

Try this instead:

counter = 0;
for (var content in array)
{
    window["data" + counter.toString()] = content;
    counter++;
}
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
  • 3
    I would recommend you not to use `for..in` for array .. And content is `0,1` not array elements and it's `counter++` not `content++` – Prasath K May 29 '13 at 10:13