FFLNVB
FFLNVB

Reputation: 147

Can't push to Array inside Array

var tags = new Array();
var tags[4]= new Array();
tags[4].push("Hello");

Somehow this doesnt work, console Says on line two that there's an unexpected Token... Can you help me somehow? Its an Array inside an Array. I simplified the code, because the rest is right.

Thx

Upvotes: 1

Views: 353

Answers (6)

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

It's a simple mistake to make. Just remove var from line 2...

var tags = new Array();
tags[4]= new Array();
tags[4].push("Hello");

tags[4] is already available by declaring tags on line 1.

Upvotes: 6

var tags[4] // is incorrect.
// use this
tags[4]= new Array();
tags[4].push("Hello");

var keyword creates a variable so old value is lost .

Upvotes: 3

Navin
Navin

Reputation: 604

Remove var before tag[4]

Try this instead.

var tags = new Array();
tags[4]= new Array();
tags[4].push("Hello");

Upvotes: 0

cajunc2
cajunc2

Reputation: 216

The array tags has already been initialized, so you don't need var on the second line. Remove it and the code works as expected.

Upvotes: 2

Tibos
Tibos

Reputation: 27823

Remove the var before tags[4]. tags is the variable, tags[4] is a property of the object referenced by that variable, not another variable.

var tags = new Array();
tags[4]= new Array();
tags[4].push("Hello");

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

var tags[4] is incorrect. Just tags[4] is needed.

Upvotes: 12

Related Questions