JavaScript
// create an array (via array literal) and add items to it
var names = [];
names[0] = "Joe"
names[1] = "Sue";
// create an array (via array literal) and assign values to it
var names = ["Joe", "Sue"];
// create an array (via array constructor) and add items to it
var names = new Array();
names[0] = "Joe";
names[1] = "Sue";
// create an array (via array constructor) and assign items to it
var names = new Array("Joe", "Sue");
// add an item to the end of an array
names.push("Jim");
// remove an item from the end of an array
names.pop();
// find the index of an item in an array
var pos = names.indexOf("Sue");
// get the length of an array
var len = names.length;
// convert an array into a string with a separator
var namesString = names.join(", ");
// loop through an array (for loop)
for (var i = 0; i < names.length; i++) {
console.log(names[i]);
}
// loop through an array (foreach loop)
names.forEach(function(item, index, array) {
console.log(item, index);
});
// loop through an array (for in loop)
for (var i in names) {
console.log(names[i]);
}
// create a multi-dimensional array
var pets = [
['Dogs', 2],
['Cats', 1]
];
// access an item in a multi-dimensional array
console.log(pets[1, 0]); // Cats
// arrays can contain multiple data types
var arr = ["Joe", 1, 2.5];
// sort an array of strings (only use this approach for strings)
names = names.sort(); // ascending order
names = names.reverse(); // descending order (for this to work, need to call sort() first)
// sort an array of numbers (only use this approach for numbers)
var numbers = [4, 10, 1, 5, 25, 15];
numbers.sort(function(a, b) {return a - b}); // ascending order
numbers.sort(function(a, b) {return b - a}); // descending order