JavaScript Array methods and Array-like Objects

The JavaScript array methods are purposely defined to be generic, so that they work correctly when applied to array-like objects in addition to true arrays. In ECMAScript 5, all array methods are generic. In ECMAScript 3, all methods except toString() and toLocaleString() are generic. (The concat() method is an exception: although it can be invoked on an array-like object, it does not property expand that object into the returned array.) Since array-like objects do not inherit from Array.prototype, you cannot invoke array methods on them directly. You can invoke them indirectly using the Function.call method, however:

// An array-like object
var a = {"0":"a", "1":"b", "2":"c", length:3}; 
Array.prototype.join.call(a, "+");  // => "a+b+c"
Array.prototype.slice.call(a, 0);   // => ["a","b","c"]: true array copy
Array.prototype.map.call(a, function(x) { 
    return x.toUpperCase(); // => ["A","B","C"]
})                                 

JavaScript: The Definitive Guide

0%