Data Structures and Iteration
We have met one data structure, the array. Arrays are indexed by nonnegative integers and are heterogeneous sequences. They allow us to store a collection of objects under a single name and they provide a convenient means for access to the items they contain.
Now we will meet another data structure, the nodelist or HTML
Collection. Nodelists are collections of HTML elements. Nodelists, like
arrays, have a length
property.
You can index into them using []. You cannot, however, use array
methods such as
push
, pop
, shift
, and
unshift
on them.
How do I get a nodelist?
The document
object has several answers.
document.getElementsByTagName
You specify a tag type to this function and it gives you a nodelist of all elements of that tag's type on a page.document.getElementsByClassName
You specify a class to this function and it gives you a nodelist of all elements marked with this class.document.querySelectorAll
You specify a CSS selector and all elements selected by that selector are returned in a nodelist.
How do I do something to every item in an array or
nodelist? It's time for a new construct, the for
boss statement. It comes in two important flavors.
The C-Style for
loop
for(init; test; between) { block o' code }
- init runs and is never seen again.
- test runs. If it evaluates to false, loop ends. Otherwise, the block runs.
- between runs
- test &rrar; block →between until the test fails.
The for of
loop
for(item of collection) { block o' code }
The block is executed for each item in the collection.
let x = [1,2,3,4,5,6]; C style for(let k = 0; k < x.length; k++) { console.log(x[k]); } for of: for(item of x) { console.log(item); }