Learn Coding From Zero

JavaScript Basic: Study Note For Array Iteration

Array iteration refers to iterating over a list or an array. Basically, it loops through that array and do something to each item or with each item.

Use For Loop

We use for loop to loop over an array. In order to do that, we need to make use of the array’s length property.

For example, if we want to print out each item from an array, we need to recall the index of each item.

In this case, we want to print out each letter from the array, so we have to type the code for times. It is repeating a lot. Image we have hundred or thousands data and print it all out, it will drive us crazy.

Therefore, we use a loop to help automate this process because what we are doing here is the same operation. Using for loop can save our time and make the code clean. 

var letters = [“a”, “b”, “c”, “d”]

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

In the for loop, we have our variable i start with 0 because that is the first index in an array. Then, we add one to it each time through the loop. For the condition, the i is less than the length of the array which is 4.

Use forEach ()

JavaScript provides an easy built-in way of iterating over an array: forEach(). ForEach() is a method that’s defined on every single array. It takes a function as an argument such as:

arr.forEach(someFunction)

For the same example, we use forEach() to present:

var letters = [“a”, “b”, “c” “d”];
letters.forEach(function(letters){
console.log(letters);
});

We use forEach method, and it gives us the same result.

For Loop V.S. forEach()

The key difference is the fact that in a for loop we are dealing with a number. We are going from a number from 0 up until the end of the array and use that number to access the array letters.

In a forEach(), we are doing with is a name that we are created in a temporary placeholder letters and we use that inside of a function.

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s