For Loop Practice

Page section: playground
More on loops

Loops can print out each item of the array. This works well in the console and with alert() as one follows the next. However when trying to write to the page, say using innerHTML each time the loop repeats the innerHTML is rewritten and the end result is that you see only the last result.

The key is +=.

So this works:

`ul.innerHTML += `<li> ${scientificFruit[i]} </li>`;

    How it’s done

    The first button uses a regular for loop:

    function listScientificFruit() {
        const ul = document.querySelector('section>ul');
    
        for (let i = 0; i < scientificFruit.length; i++ ) {
            ul.innerHTML += `<li> ${scientificFruit[i]} </li>`;
        }
    };
    

    The second part uses a for ... of loop.

    function listFruit() {
        const para = document.querySelector('section>p');
    
        for (let frt of fruit) {
            console.log(frt);
            para.innerHTML += `${frt}, `;
        }
    };
    

    A different way

    So a different way to use a loop is by attaching the array to the start of the for loop. So with an array called myArray it would be: myArray.forEach

    const myArray = ['a', 'b', 'c']; 
    
      myArray.forEach(function(entry) {
          // console.log(entry);
      paragraph.innerHTML += `${entry}, <br>`;
    
      });
    

    Conclusion

    When looping through arrays the newer for ... of loops are simpler to write than a regular for loop.

    Remember that when using loops on things like .innerHTML to use += to avoid rewriting over the same thing each loop.

    One issue with using += is that it outputs again and again every time you press the button. My fix for this is simply to clear anything in the HTML element by adding .innerHTML = '' at the start of function.

    Looking stuff up online is probably better than trying to figure things out especially when there’s lots you don’t know, eg. +=.

    View contents of: /static/js/tryout-arrays.js
    const fruit = ["apples", "bananas", "cantaloupe", "dorians"];
    
    const scientificFruit = [
      "Bell pepper",
      " Chile pepper",
      " Corn kernel",
      " Cucumber",
      " Eggplant",
      " JalapeƱo",
      " Olive",
      " Pea",
      " Pumpkin",
      " Squash",
      " Tomato",
      " Zucchini",
    ];
    
    const todos = [
      {
        id: 1,
        text: "Take out rubbish",
        isCompleted: true,
      },
      {
        id: 2,
        text: "Meet with boss",
        isCompleted: true,
      },
      {
        id: 3,
        text: "Dental appointment",
        isCompleted: false,
      },
    ];
    
    function showFruit() {
      document.getElementById("fruitlist").innerHTML = fruit;
    }
    
    function fruitLoops(frt) {
      document.getElementById("fruit-loops").innerHTML += frt + '<br>';
    }
    
    const butt1 = document.getElementById("listfruit");
    
    butt1.addEventListener("click", () => {
      document.getElementById("fruitlist").innerHTML = fruit;
    });
    
    const butt2 = document.getElementById("fruit2");
    
    butt2.addEventListener("click", function () {
      document.getElementById("fruitlist").innerHTML = fruit[1];
    });
    
    const butt3 = document.getElementById("scientific");
    
    butt3.addEventListener("click", function () {
      document.getElementById("fruitlist").innerHTML = scientificFruit;
    });
    
    const butt39 = document.getElementById("copying");
    
    butt39.addEventListener("click", function () {
      const otherFruit = fruit.slice(1, 3);
      console.log("what apphen?");
      alert(`A new array called otherFruit now contains ${otherFruit}`);
    });
    
    // For buttons showing Array Methods
    
    let myVar = [[1, "tree"], 2, 3, 4, 5, 6];
    const mySubVar = ["frog", "Linsang", "stink badger"];
    
    const showMyVar = document.getElementById("show-my-var");
    const smvList = document.getElementById("smv-list");
    
    function listMyVar() {
      smvList.innerHTML = ``;
      for (let i = 0; i < myVar.length; i++) {
        smvList.innerHTML += `<li>${myVar[i]}</li>`;
      }
    }
    
    showMyVar.addEventListener("click", () => {
      listMyVar();
    });
    
    const resetMyVar = document.getElementById("reset-my-var");
    
    resetMyVar.addEventListener("click", () => {
      myVar = [[1, "tree"], 2, 3, 4, 5, 6];
      listMyVar();
      //   alert("reset");
    });