Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

6. Arrays > Array-Like Objects

Array-Like Objects

As we’ve seen, arrays are objects that have a length property with special behavior. An “array-like” object is an ordinary JavaScript object that has numeric properties names and a length property. These “array-like” objects actually do occasionally appear in practice, and although you cannot directly invoke array methods on them or expect special behavior from the length property, you can still iterate through them with the same code you’d use for a true array:

// An array-like object
var a = {"0":"a", "1":"b", "2":"c", length:3};  
// Iterate through it as if it were a real array
var total = 0;
for(var i = 0; i < a.length; i++)
    total += a[i];

Many array algorithms work just as well with array-like objects as they do with real arrays and the JavaScript array methods are purposely defined to be generic, so that they work correctly when applied to array-like objects. 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 (see Indirect Invocation), however:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint