Array
The Array
constructor creates array objects:
> var a = new Array(1, 2, 3);
This is the same as the array literal:
> var a = [1, 2, 3]; //recommended
When you pass only one numeric value to the Array
constructor, it's assumed to be the array length:
> var un = new Array(3); > un.length; 3
You get an array with the desired length and if you ask for the value of each of the array elements, you get undefined
:
> un; [undefined, undefined, undefined]
There is a subtle difference between an array full of elements and array with no elements, but just length:
> '0' in a; true > '0' in un; false
This difference in the Array()
constructor's behavior when you specify one versus more parameters can lead to unexpected behavior. For example, the following use of the array literal is valid:
> var a = [3.14]; > a; [3.14]
However, passing the floating-point number to the Array
constructor is an error:
> var a = new Array(3.14); Range Error: invalid array length
The Array.prototype members
The following are the list of all the elements of an Array
:
Property/method |
Description |
|
The number of elements in the array: > [1, 2, 3, 4].length; 4
|
|
Merges arrays together: > [1, 2].concat([3, 5], [7, 11]); [1, 2, 3, 5, 7, 11]
|
|
Turns an array into a string. The separator parameter is a string with comma as the default value: > [1, 2, 3].join(); "1,2,3" > [1, 2, 3].join('|'); "1|2|3" > [1, 2, 3].join(' is less than '); "1 is less than 2 is less than 3"
|
|
Removes the last element of the array and returns it: > var a = ['une', 'deux', 'trois']; > a.pop(); "trois" > a; ["une", "deux"]
|
|
Appends elements to the end of the array and returns the length of the modified array: > var a = []; > a.push('zig', 'zag', 'zebra','zoo'); 4
|
|
Reverses the elements of the array and returns the modified array: > var a = [1, 2, 3]; > a.reverse(); [3, 2, 1] > a; [3, 2, 1]
|
|
Like > var a = [1, 2, 3]; > a.shift(); 1 > a; [2, 3]
|
|
Extracts a piece of the array and returns it as a new array, without modifying the source array: > var a = ['apple', 'banana', 'js', 'css', 'orange']; > a.slice(2,4); ["js", "css"] > a; ["apple", "banana", "js", "css", "orange"]
|
|
Sorts an array. Optionally accepts a callback function for custom sorting. The callback function receives two array elements as arguments and should return
An example of a custom sorting function that does a proper numeric sort (since the default is character sorting):
function customSort(a, b) { if (a > b) return 1; if (a < b) return -1; return 0; } Example use of sort(): > var a = [101, 99, 1, 5]; > a.sort(); [1, 101, 5, 99] > a.sort(customSort); [1, 5, 99, 101] > [7, 6, 5, 9].sort(customSort); [5, 6, 7, 9]
|
|
Removes and adds elements at the same time. The first parameter is where to start removing, the second is how many items to remove and the rest of the parameters are new elements to be inserted in the place of the removed ones: > var a = ['apple', 'banana', 'js', 'css', 'orange']; > a.splice(2, 2, 'pear', 'pineapple'); ["js", "css"] > a; ["apple", "banana", "pear", "pineapple", "orange"]
|
|
Like > var a = [1, 2, 3]; > a.unshift('one', 'two'); 5 > a; ["one", "two", 1, 2, 3]
|
ECMAScript 5 additions to Array
Following are the ECMAScript 5 additions to Array
:
Property/method |
Description |
|
Tells if an object is an array because > var arraylike = {0: 101, length: 1}; > typeof arraylike; "object" > typeof []; "object"
Neither is duck-typing (if it walks like a duck and quacks like a duck, it must be a duck):
typeof arraylike.length; "number"
In ES3 you need the verbose:
> Object.prototype.toString .call ([]) === "[object Array]"; true > Object.prototype.toString.call (arraylike) === "[object Array]"; false
In ES5 you get the shorter:
Array.isArray([]); true Array.isArray(arraylike); false
|
|
Searches the array and returns the index of the first match. Returns > var ar = ['one', 'two', 'one', 'two']; > ar.indexOf('two'); 1 > ar.indexOf('two', 2); 3 > ar.indexOf('toot'); -1
|
|
Like > var ar = ['one', 'two', 'one', 'two']; > ar.lastIndexOf('two'); 3 > ar.lastIndexOf('two', 2); 1 > ar.indexOf('toot'); -1
|
|
An alternative to a > var log = console.log.bind(console); > var ar = ['itsy', 'bitsy', 'spider']; > ar.forEach(log); itsy 0 ["itsy", "bitsy", "spider"] bitsy 1 ["itsy", "bitsy", "spider"] spider 2 ["itsy", "bitsy", "spider"]
Optionally, you can specify a second parameter: the object to be bound to this inside the callback function. So this works too:
> ar.forEach(console.log, console);
|
|
You provide a callback function that tests each element of the array. Your callback is given the same arguments as
If all elements satisfy your test,
> function hasEye(el, idx, ar) { return el.indexOf('i') !== -1; } > ['itsy', 'bitsy', 'spider']. every(hasEye); true > ['eency', 'weency', 'spider'].every(hasEye); false
If at some point during the loop it becomes clear that the result will be
> [1,2,3].every(function (e) { console.log(e); return false; }); 1 false
|
|
Like > ['itsy', 'bitsy', 'spider'].some(hasEye); true > ['eency', 'weency', 'spider'].some(hasEye); true
|
|
Similar to > ['itsy', 'bitsy', 'spider'].filter(hasEye); ["itsy", "bitsy", "spider"] > ['eency', 'weency', 'spider'].filter(hasEye); ["spider"]
|
|
Similar to > function uc(element, index, array) { return element.toUpperCase(); } > ['eency', 'weency', 'spider'].map(uc); ["EENCY", "WEENCY", "SPIDER"]
|
|
Executes your callback for each element of the array. Your callback returns a value. This value is passed back to your callback with the next iteration. The whole array is eventually reduced to a single value: > function sum(res, element, idx, arr) { return res + element; } > [1, 2, 3].reduce(sum); 6
Optionally you can pass a start value which will be used by the first callback call:
> [1, 2, 3].reduce(sum, 100); 106
|
|
Like > function concat( result_so_far, el) { return "" + result_so_far + el; } > [1, 2, 3].reduce(concat); "123" > [1, 2, 3].reduceRight (concat); "321"
|
ES6 addition to arrays
Following are the addition to arrays:
|
The const arrayLike = { length: 2, 0: 'a', 1: 'b' }; const arr = Array.from(arrayLike); for (const x of arr) { // OK, iterable console.log(x); } // Output: // a // b
|
|
Creates an array out of the items passed to the method let a = Array.of( 1,2,3,'foo'); console.log(a); //[1, 2, 3, "foo"]
|
|
The result of these methods is a sequence of values. These methods returns an iterator of keys, values and entries respectively. let a = Array.of(1,2, 3,'foo'); let k,v,e; for (k of a.keys()) { console.log(k); //0 1 2 3 } for (v of a.values()) { console.log(v); //1 2 3 foo } for (e of a.entries()){ console.log(e); } //[[0,1],[1,2],[2,3] [3,'foo']]
|
|
Returns the first array element for which the callback function returns [1, -2, 3].find(x => x < 0) //-2
|
|
Returns the index of the first element for which the callback function returns true. If there is no such element, it returns [1, -2, 3].find(x => x < 0) //1
|
|
It fills an array with the given value: const arr = ['a', 'b', 'c']; arr.fill(7) [ 7, 7, 7 ] You can specify start and end ranges. ['a', 'b', 'c'].fill(7, 1, 2) [ 'a', 7, 'c' ]
|