0xmtn
0xmtn

Reputation: 2670

Javascript - Assign an array to a key of another one

So I've been checking around for a while but couldn't find anything...at least useful. So here is what I want to accomplish:

  a = new Array();
  b = new Array();
  a[0] = 1;
  a[1] = 2;
  b[0] = a;

It is not do-able, at least with the way above. How can I do that? Is there any other way to do this? Of course, there are plenty of ways to do what want to do but I want to do this with arrays. ;)

Thanks in advance ;)

Upvotes: 1

Views: 106

Answers (2)

Dagg Nabbit
Dagg Nabbit

Reputation: 76776

You can (and probably should) do something like this instead:

var a = [1, 2], 
    b = [a];

...or you could do it like this.

var a, b /* other vars */;
//other code
b = [(a=[1, 2])];

It's generally considered good practice to use the literal syntax when declaring arrays and objects instead of invoking the constructor, so var foo = [], bar = {};.

Also, you should use the var keyword when defining variables, so they don't leak into the global scope.

Upvotes: 0

MarkSmits
MarkSmits

Reputation: 538

Only thing I can think of is declaring the variables a and b, the rest is all valid if you ask me.

var a = new Array(),
    b = new Array();

a[0] = 1;
a[1] = 2;
b[0] = a;

http://jsfiddle.net/LvELV/

Upvotes: 3

Related Questions