Looping through array in JavaScript
// looping an HTMLCollection using for
var TheadRows = document.getElementById('table').tHead.rows[0].cells
for (var i = 0; i < TheadRows.length; i++) {
console.log(TheadRows[i].innerText)
};
// looping with Array.prototype.forEach (only for HTMLCollection object)
// using for Each is not suitable for arrays (i.e., indexed lists) as it is supposed to be used with objects (i.e., named parameters)
// however you can use forEach.call to get it to work
[].forEach.call(TheadRows, function(el) {
console.dir(el)
});
// for in however is designed to be used with objects
for (var property in TbodyRows) {
debug(TbodyRows[property])
}
// in ES6 can use for...of
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
for (el of TheadRows) {
console.log(el.id);
}
// another example
bullets.forEach((bullet) => {
});
// vs...
for(let bullet of bullets) {
}
// something else
[].forEach.call(document.querySelectorAll('.foo'), (foo) => {
foo.classList.add('bar');
});
[...document.querySelectorAll('.foo')].forEach((foo) => {
foo.classList.add('bar');
});
Array.from(document.querySelectorAll('.foo')).forEach((foo) => {
foo.classList.add('bar');
});
for(let foo of document.querySelectorAll('.foo')) {
foo.classList.add('bar');
}