Title: Arrays Info (Cheat Sheet)
Course: Fall 2023 - WEBD 164 (41934) > Section: Week 7 (Oct 2) How to Work with Arrays – basic concepts

Creating a Numeric Array

Unlike most other types of JavaScript variables, you typically need to declare an array before you use it. The following example creates an array with four elements:

scores = new Array(4);

To assign a value to the array, you use an index in brackets. Indexes begin with 0, so the elements of the array in this example would be numbered 0 to 3. These statements assign values to the four elements of the array:

scores[0] = 39; scores[1] = 40; scores[2] = 100; scores[3] = 49;

You can also declare an array and specify values for elements at the same time. This statement creates the same scores array in a single line:

scores = new Array(39,40,100,49);

In JavaScript 1.2 and later, you can also use a shorthand syntax to declare an array and specify its contents. The following statement is an alternative way to create the scores array:

scores = [39,40,100,49];

Create an String Array

An array can be defined in three ways.

The following code creates an Array object called myCars:

1:

var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab";       // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";

2:

var myCars=new Array("Saab","Volvo","BMW"); // condensed array

3:

var myCars=["Saab","Volvo","BMW"]; // literal array

Slicing an Array:

var languages = ["php", "javascript", "java", "action script"];
document.write(languages.slice(0,1) + "
");
document.write(languages.slice(1) + "
");
document.write(languages.slice(-2) + "
");
document.write(languages);


php
javascript,java,action script
java,action script
php,javascript,java,action script

Sorting an Array

nums = new Array(30, 10, 200, 4);
sortednums = nums.sort(num);


Pop()

var a = [1,2,3];

a.pop(); //-> 3

a; //-> [1,2]

Push()

var a = [1,2];

a.push(3, 4); //-> 4

a; //-> [1,2,3,4]

Attachments

- Arrays.htm