-
Notifications
You must be signed in to change notification settings - Fork 0
Description
How Do We Access Every Piece of Array? --> The solution is Array Iteration!
Sometimes you need to access each piece of information in an array, e.g. comments, posts, etc.
for loop
This is used to apply a certain instruction to every piece of the array. You use for as you would any other function.
var comments = ["blabla", "this is cool", "Hey what's up?"]
for (var i = 0; i < comments.length; i++) {
console.log(comments[i])
}This is just a meaningless instruction. Here's a more specific (and typical) example:
for (var i = 0; i < comments.length; i++) {
makecommentHTML(comments[i]);
}Note: "i" (index no.) always begins with 0.
.forEach
This is much nicer to use compared to "for loop"! We're basically passing one function into another (meaning that we're treating one of the functions as an argument - yes, pretty damn cool). Check this out:
var comments = ["blabla", "this is cool", "Hey what's up?"]
comments.forEach(whateverfunction(){
console.log("Say something here!");
});A more specific example:
var comments = ["blabla", "this is cool", "Hey what's up?"]
comments.forEach(function(SayThankYou) {
console.log ("Thank You " + SayThankYou);
});
// Thank You blabla
// Thank You this is cool
// Thank You Hey what's up?Another way of doing this (hopefully clearer way) is to actually name the accursed function before putting it into a forEach, like so:
var comments = ["blabla", "this is cool", "Hey what's up?"]
function printComment(comments) {
console.log(comments + "_printed");
}
printComment("blabla") // blabla_printed Which means that you can just do this after that:
comments.forEach(printComment)
// blabla_printed
// this is cool_printed
// Hey what's up?_printed(I know! It's so logical it's just beautiful!)