JavaScript - Arrays - Basic
// JavaScript - Arrays - Basic
var a = ["dog", "cat", "hen"];
var a = new Array();
a[0] = "dog";
a[1] = "cat";
a[2] = "hen";
var movies = new Array( 'Transformers', 'Avatar', 'Indiana Jones');
var movies = ['Transformers', 'Avatar', 'Indiana Jones'];
// Join elements of an array into a string separated by a separator:
var str = arr.join(',');
// Join two arrays to create a new array:
var arr1 = [];
var arr2 = [];
var arr3 = [];
var arr1 = arr1.concat(arr2, arr3);
The concat method can take multiple arrays as parameters. It returns a new
array and does not change the existing array (the one that is used to invoke
the concat method).
// Find the largest number in an array
var numbers = [3, 342, 23, 22, 124];
numbers.sort(function(a,b) {return b - a}); // the sort function directly modify the array in-place
var result = numbers[0];
var result = Math.max(12, 123, 3,2, 433, 4);
delete myArray[5];
// To sort an array:
var numbers = [3, 342, 23, 22, 124];
numbers.sort(comparisonFunction);
The comparison function should take p1 and p2, returns negative if p1 < p2,
zero if equal, and positive if p1 > p2.
numbers.sort(function(a,b) {return b - a}); // sort descending
numbers.sort(function(a,b) {return a - b}); // sort ascending
// Some way to empty an array:
this.options.length = 0;
this.options = new Array();
// isArray:
Array.isArray(obj)
Array.isArray([1, 2, 3]); // true
Array.isArray({foo: 123}); // false
Array.isArray("foobar"); // false
Array.isArray(undefined); // false
Array.isArray(arguments); // false
// Array.prototype.pop()
The pop() method removes the last element from an array and returns that element.
This method changes the length of the array.
arr.pop()
The pop method removes the last element from an array and returns that value to
the caller.
// Array.prototype.push():
The push() method adds one or more elements to the end of an array and returns
the new length of the array.
arr.push([element1[, ...[, elementN]]])
var a = [1, 2, 3];
a.push(4, 5);
console.log(a); // [1, 2, 3, 4, 5]
page revision: 3, last edited: 14 Nov 2016 20:12





