Javascript

Home Load Console Selectors CSS Form Strings If Else Array Reg Exp Date & Time setTimeout JSON Loops Objects Animation Fat Arrow Class Import IIFE undefined Tabulator.js ES6 Event Listeners AJAX Hide Elements Create Elements Checkbox ejs
O O

Weather Controls

Time Of Day
Rain
Wind Speed
Wind Direction
Clouds

Javascript : Loops

2022-07-18

Loop Arrays

var food = ["burrito","taco","quesadilla"]

// for
for (var i = 0; i < food.length; i++) {
    console.log(food[i])
}

// forEach
food.forEach(function(item, i) {
    console.log(item, i);
    console.log(food[i])
});

// for of
for (var item of food) {
   console.log(item);
}

Loop Objects

var person = { name: "Rob", height: 74, isMale: true };

// for in
for (var key in person) {
  console.log(key, person[k]);
  if (person.hasOwnProperty("isMale") && obj.isMale) {...}
}

// convert the object to arrays, then loop the array
var keys = Object.keys(person);
console.log(keys); // ["name", "height", "isMale"]

var values = Object.values(person);
console.log(values); // ["Rob", 74, true]

var entries = Object.entries(person);
console.log(entries); // [["name", "Rob"], ["height", 74, ["isMale", true]]

Loop through all first table td

var tables = document.getElementsByTagName("table");
for (var i = 0; i < tables.length; i++) {
    var td = tables[i].querySelectorAll('tr > td:first-child');
    for (var j = 0; j < td.length; j++) {
        console.log(td[j])
    }
}