concept arrays in category javascript

appears as: rrays
Secrets of the JavaScript Ninja, Second Edition

This is an excerpt from Manning's book Secrets of the JavaScript Ninja, Second Edition.

Even though all modern JavaScript engines now support a forEach method on arrays, we’ll build our own (simplified) version of such a function in the next listing.

Now that we’ve spent some time wrangling the particularities of object-orientation in JavaScript, we’ll move on to a closely related topic: collections of items. We’ll start with arrays, the most basic type of collection in JavaScript, and look at some array peculiarities you may not expect if your programming background is in another programming language. We’ll continue by exploring some of the built-in array methods that will help you write more elegant array-handling code.

Listing 9.13. Simulating array-like methods
<body> <input id="first"/> <input id="second"/> <script> const elems = { length: 0, #A add: function(elem){ #B Array.prototype.push.call(this, elem); #B }, #B gather: function(id){ #C this.add(document.getElementById(id)); #C }, #C find: function(callback){ #D return Array.prototype.find.call(this, callback); #D } #D }; elems.gather("first"); assert(elems.length === 1 && elems[0].nodeType, "Verify that we have an element in our stash"); elems.gather("second"); assert(elems.length === 2 && elems[1].nodeType, "Verify the other insertion"); elems.find(elem => elem.id === "second"); assert(found && found.id === "second", "We've found our element"); </script> </body> #A - Stores the count of elements. The array needs a place to store the number of items it’s storing. #B - Implements the method to add elements to a collection. The prototype for Array has a method to do this, so why not use it instead of reinventing the wheel? #C - Implements the gather method to find elements by their id values and add them to the collection #D - Implements the method to find elements in the collection. Similar to the add method, it reuses the existing find method accessible to arrays. !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[]"} !@%STYLE%@!
  • Iterating (or traversing) through arrays