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()
andtoLocaleString()
are generic. (Theconcat()
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 fromArray.prototype
, you cannot invoke array methods on them directly. You can invoke them indirectly using theFunction.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