0

I can't find this answer anywhere. I am learning javascript on myself so I guess this is basic.

I want to assign a variable "count" as the subscript of an array.

var firstnumber = 200;
var count = 1;
var a;
a[count] = firstnumber;

therefore to achieve the result as a[count] = 200

is there anyway to do this?

2 Answers2

1

Declare your variable and initialize it as an array

var a = [];

William Barbosa
  • 4,936
  • 2
  • 19
  • 37
  • That would be a [*VariableDeclaration*](http://ecma-international.org/ecma-262/5.1/#sec-12.2) with optional *intialiser*, in this case an [*Array initialiser*](http://ecma-international.org/ecma-262/5.1/#sec-11.1.4). :-) – RobG May 16 '14 at 02:05
0

See the comments below:

var a = new Array();  //create an Array
var count = 0;  //arrays start at index 0
var firstnumber = 200;
var secondnumber = 300;

a[count] = firstnumber; //set the first element of the array to firstnumber

count = 1;
a[count] = secondnumber; //set the second element of the array to secondnumber

alert(a[0]);  //displays 200 in an alert window
alert(a[1]);  //displays 300 in an alert window
Edwin Torres
  • 2,774
  • 1
  • 13
  • 15