97 For in Loop example in JS - JavaScript Tutorial 2018

preview_player
Показать описание

Learn HTML, CSS and JavaScript

JavaScript Tutorial 2018

This is a Javascript tutorial from scratch for any beginner. Use the above link to watch the full JS video tutorial..

Hi and welcome back.

So right now we are looking at the for-in loop in JavaScript.

In the last video, we saw an example using an object.

Let’s convert this to an array.

Let’s just call it ‘character’ still.

But, we remove this.

We remove that.

We make it square brackets.

And then, let’s make that, that, we make that, that onto that so that this can be different elements of our array.

So in this case also, let me comment this one out.

If I alert(c), you know that arrays are, arrays are zero based indexes.

So we expect to see 0, 1, 2 as our results.

So it’s going to bring back the indexes.

Since this is an array, it’s going to bring back indexes of these elements.

So if we alert(c), let’s run that.

It’s going to bring 0, 1, 2, 3, 4, 5, 6 until the last element of the array.

So they’re one, 0, 1, 2, 3, 4, 5.

So if you want to find the elements in the arrays, we can do what we did the last time.

So it will bring back element.

Let’s say we want to say ‘element at’, element at this index is.

And then how do you access elements in an array.

You access them this very way, so the name of the array and the index of the array.

And if we run that, it will show us that “element at 0 is name”, “element at 1 is Joey”, “element at 2 is show”, “element at 3”, all the way until we reach the last element.

So the point of this video is to show that whether it’s an array or an object, the for-in loop will bring back the name or the index.

In this case, since we’re using an array, it will bring back the name of the index.

So, that’s something to note about the for-in loop.

It brings back the name which is also called the key in case of an object or it will bring back the index in case of an array.

So if you want to iterate through elements in an object or in an array, the for-in loop will not bring back the values.

And if you want to get back the values, you have to do a bunch of other things like I did here.

You see for me to access the actual element in the array, I had to do that.

So in the next video, let’s look at the for-of loop and what the for-of loop does.

The for-of loop is the same as the for-in loop except that the for-of will bring back the values.

So let’s continue in the next video.

.
GET SOCIAL WITH ME:
Рекомендации по теме
visit shbcf.ru