Arrays Flashcards
declaring
Having infomation in a array
var numbers = [1,2,3,4,5,6];
empty arrays
To add information into a array
var numbers = [ ]
pushing
In JavaScript, the .push() function is used to add another value to the end of an existing array. Add .push to
the array’s name, along with the new value to be added in parentheses.
cars.push(“Kia”);
positions
To access a particular value within the array, use the specific position or index of the value. Remember that
in JavaScript, like in most programming languages, the first position is position zero. To store a value into a
specific position within the array, write the index inside the square brackets:
cars[0] = “Chevrolet”;
Likewise, to display the value stored in a specific position within the array, write the index inside the square
brackets:
document.write(cars[2]);
splitting strings into arrays
A string can be split into an array where each word is stored in successive positions in the array. This is done
using the .split() method. You should specify what character to use to determine how to split the string,
such as a space or a comma.
var array1 = string1.split(“ “);
popping
The .pop() function is used to remove the last element from an existing array. Add .pop to the array’s name.
var lastValue = cars.pop();
Array
An array is a structure that holds more than one value at a time. Most programming languages, including
JavaScript, use square brackets to indicate an array.
var cars = [“Ford”, “Honda”, “Audi”];
Joining
An array can be made back into a string using the .join() method. You should specify what character to use
when joining the contents of the array back together, such as a space or a comma.
var string1 = array1.join(“ “);
Sorting
An array can be sorted in alphabetic order using the .sort() method.
var sorted = array1.sort();