Looping arrays


How can I loop in an array? Instead of writing out an array like
var x = [1,2,3,4,5,6,7,8,9,10];
How can I make it so a loop will automatically do it?
I tried this, altough it only returns one value, and not all 10.

for (var i = 1; i<11; i++) {
    var numbers = [i];


You only get one value because by putting [i], you're making a nameless array with the value of i. If you want it to print out all the elements in the array, do something like this.
for (var i = 0; i < 10; i++) {


Since array sizes can change, we are better prepared if we use the array's length property in the conditional expression.

i < x.length;

We access the members of the array through their index:


Now to build an array whose members are in a sequence (meaning the difference is the same between adjacent members) we can do what you have, except we need to define an empty array to begin with.

 var numbers = [];

If you are not yet familiar with Array.push() then we can use a slightly different approach.

var numbers = new Array(10);

This array will have 10 members, but none are yet defined. It does have a length property, though, so we can use that in a for statement:

for (var i = 0; i < numbers.length; i++) {
    numbers[i] = i + 1;

The push() method is as follows:

var numbers = [];
for (var i = 1; i < 11; i++) {