JavaScript learning - Array object

Defining arrays

Array objects are used to store a series of values in separate variable names.
We use the keyword new to create array objects. The following code defines an array object called myArray:

var myArray=new Array();

There are two ways to assign values to an array (you can add as many values as you want, just as you can define as many variables as you want).
1,

var mycars=new Array()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"

You can also use an integer argument to control the size of the array:
var mycars=new Array(3)
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"

2,

var mycars=new Array("Saab","Volvo","BMW");

Note: if you need to specify a numeric or logical value in an array, the variable type should be a numeric or boolean variable, not a character variable.

Access array

By specifying the array name and index number, you can access a specific element.

document.write(mycars[0]) // Output: Saab

Modify the values in an existing array

To modify the values in an existing array, simply add a new value to the specified subscript number:

mycars[0]="Opel";

Now?

document.write(mycars[0]);// Output: Opel

Sample code

Create array

var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"

for (i=0;i<mycars.length;i++)
{
document.write(mycars[i] + "<br />")
}

For… In statement

var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"

for (x in mycars)
{
document.write(mycars[x] + "<br />")
}

Merge two arrays - concat()

var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"

var arr2 = new Array(3)
arr2[0] = "James"
arr2[1] = "Adrew"
arr2[2] = "Martin"

document.write(arr.concat(arr2))

Using the elements of an array to form a string - join()

var arr = new Array(3);
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"

document.write(arr.join());

document.write("<br />");

document.write(arr.join("."));

Array of literals - sort()

var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"

document.write(arr + "<br />")
document.write(arr.sort())

Array of numbers - sort()

function sortNumber(a, b)
{
return a - b
}

var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"

document.write(arr + "<br />")
document.write(arr.sort(sortNumber))

Posted on Wed, 01 Jul 2020 10:33:01 -0400 by sheephat