TomRed.net

  • Increase font size
  • Default font size
  • Decrease font size
Subscribe Bookmark and Share
Home Tutorials CSS JavaScript Array Declaration Creation or Adding Elements

JavaScript Array Declaration Creation or Adding Elements

User Rating: / 0
PoorBest 

There are a number of ways of creating or declaring arrays in JavaScript. The first way uses the new key word. You can then add elements to this using the assignment operator "=". In the example below we create and array and then add the values 0-9 into the array indexes [0] - [9]. Note: arrays in JavaScript like other languages start with index[0]. This is a trivial example but the point is clear.

var myArr = new Array();

for(var i =0; i < 10; i++){
	myArr[i] = i;
}

An alternative way of generating the same array above is to add the elements during declaration. Here the end result will be the same as the array generated in the first example.

var myArr = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

This second example is useful but when you create array you may not know what all the elements may be so it is always useful to remember that you can assign an array element a value using the scripts[index] = "some value";