7 October 2021

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.

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
}
  1. init runs and is never seen again.
  2. test runs. If it evaluates to false, loop ends. Otherwise, the block runs.
  3. between runs
  4. 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);
}