Javascript Array create

Introduction

Javascript arrays are ordered lists of data.

They can hold any type of data in each slot.

Javascript arrays are dynamically sized.

It can automatically growing to accommodate any data added to them.

We can use the Array constructor to create an array:

let colors = new Array(); 

If you know the number of items, pass it to the constructor.

The array length property will be created with that value.

For example, the following creates an array with an initial length value of 20:

let colors = new Array(20); 

The Array constructor can be passed items.

The following creates an array with three string values:

let colors = new Array("red", "blue", "green"); 

An array can be created with a single value by passing it into the constructor.

A single number argument creates an array with the given number of items.

An argument of any other type creates a one-item array for the specified value.

let colors = new Array(3);      // create an array with three items 
console.log(colors);/*from  w  w  w  . ja  v a2s  .c  om*/
let names = new Array("Javascript");  // create an array with one item, the string "Javascript" 
console.log(names);

We can omit the new operator when using the Array constructor.

It has the same result:

let colors = Array(3);      // create an array with three items 
console.log(colors);//  ww  w .  j a  v a2  s  .c  o  m
let names = Array("Javascript");  // create an array with one item, the string "Javascript" 
console.log(names);

The second way to create an array is by using array literal notation.

let colors = ["red", "blue", "green"];  // Creates an array with three strings 
let names = [];                         // Creates an empty array 
let values = [1,2,];                    // Creates an array with 2 items 



Next

Related