Section 7.8. Array-Like Objects


7.8. Array-Like Objects

A JavaScript array is special because its length property behaves specially:

  • Its value is automatically updated as new elements are added to the list.

  • Setting this property expands or truncates the array.

JavaScript arrays are also instanceof Array, and the various Array methods can be invoked through them.

These are the unique features of JavaScript arrays. But they are not the essential features that define an array. It is often perfectly reasonable to treat any object with a length property and corresponding nonnegative integer properties as a kind of array.

These "array-like" objects actually do occasionally appear in practice, and although you cannot 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. It turns out that many array algorithms work just as well with array-like objects as they do with real arrays. As long as you don't try to add elements to the array or change the length property, you can treat array-like objects as real arrays.

The following code takes a regular object, adds properties to make it an array-like object, and then iterates through the "elements" of the resulting pseudo-array:

 var a = {};  // Start with a regular empty object // Add properties to make it "array-like" var i = 0; while(i < 10) {     a[i] = i * i;     i++; } a.length = i; // Now iterate through it as if it were a real array var total = 0; for(var j = 0; j < a.length; j++)     total += a[j]; 

The Arguments object that's described in Section 8.2.2 is an array-like object. In client-side JavaScript, a number of DOM methods, such as document.getElementsByTagName(), return array-like objects.




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net