On July 9th, Brendan Eich announced that Rick Waldron had prototyped [1] two new methods for ECMAScript.next: Array.from() and Array.of(). Both methods are also useful in current JavaScript.
Array.from(arrayLike)converts an array-like object to a true array. Source code:
// Unary Array.from()
Array.from = function( arrayish ) {
return [].slice.call( arrayish );
};
Example [1]: converting an array-like DOM result into an array.
var divs = document.querySelectorAll("div");
Array.from( divs ).forEach(function( node ) {
console.log( node );
});
Explanations:
Example: invoking Array.prototype.map() generically, on the array-like arguments object.
function prefixHello(prefix) {
return Array.prototype.map.call(arguments, function(elem) {
return "Hello "+elem;
});
}
Interaction:
> prefixHello("Jane", "John")
[ 'Hello Jane', 'Hello John' ]
Array.from = function(arrayLike) {
return Array.prototype.slice.call(arrayLike);
};
Array.of([elem1], [elem2], ...)returns elem1, elem2, etc. in an array. Source code:
// Variable arity Array.of()
Array.of = function() {
return [].slice.call( arguments );
};
Usage example:
> Array.of("red", "green", "blue")
[ 'red', 'green', 'blue' ]
This method is not needed very often – array literals are usually a better solution. However, when you need a constructor function (e.g. to pass it to another function) for arrays, this method is useful. That method lets you avoid a potential pitfall of the Array constructor function: If it has several arguments, it behaves like an array literal. If it has a single argument, it creates an empty array of the given length.
> new Array(3, 4, 5)
[ 3, 4, 5 ]
> new Array(3)
[]
Array.of also ensures that your arrays don’t accidentally have holes (but I’m not sure that this feature is very imporant).
> [1,,3]
[1,,3]
> Array.of(1,,3)
Syntax error:
Array.of(1,,3)
...........^