最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - For-Of Loop vs. For Loop - Stack Overflow

programmeradmin3浏览0评论

Are these two the same or interchangeable?

What are some use cases that someone would choose one over the other?

for(let i of array){some code}
for(let i = 0; i < array.length; i++){some code}

EXAMPLE

Complete the solution so that the function will break up camel casing, using a space between words.

solution("camelCasing") == "camel Casing"

If we used this example, besides performance benefits (if any), why would someone use one loop over the other?

If there are any other examples/instances that'd be great as well.

Are these two the same or interchangeable?

What are some use cases that someone would choose one over the other?

for(let i of array){some code}
for(let i = 0; i < array.length; i++){some code}

EXAMPLE

Complete the solution so that the function will break up camel casing, using a space between words.

solution("camelCasing") == "camel Casing"

If we used this example, besides performance benefits (if any), why would someone use one loop over the other?

If there are any other examples/instances that'd be great as well.

Share Improve this question asked Mar 30, 2020 at 6:11 and1and1 3171 gold badge2 silver badges12 bronze badges 6
  • 2 In the first case i will be whatever items the array holds. In the second, i would be the indexes of the array. So, no - they aren't interchangeable. And why would they be? – VLAZ Commented Mar 30, 2020 at 6:14
  • @VLAZ so would the 2nd example be more similar to a for-in loop? – and1 Commented Mar 30, 2020 at 6:18
  • 1 In this case, yes. But in the general case for, for-in, and for-of, serve different purposes. – VLAZ Commented Mar 30, 2020 at 6:19
  • 1 Related: stackoverflow.com/questions/500504/… – Barmar Commented Mar 30, 2020 at 6:34
  • 2 I'd always use for..of loops, as they are faster to write and easier to read. Then if you can't achieve something with it (e.g. iterating backwards, or only every second element), then fall back to for. Just my 2cents though. – Jonas Wilms Commented Mar 30, 2020 at 6:36
 |  Show 1 more comment

2 Answers 2

Reset to default 18

A bit of backnowledge to explain your question:

In Javascript, Objects (among these are Arrays) store properties in key-value pairs. That means that each assigned value has a key (the property name) to access it. For example in

person[name] = 'Tom'

person is the Object, name the key and 'Tom' the corresponding value.

Arrays use indices (i.e. numbers) as keys:

array[5] = 10

Now, keep that in mind in the following explanation.

Let's start with the traditional for loop:

for(let i = 0; i < array.length; i++) {...}

This way of iterating over an array is the oldest of the bunch (as long as you are not using while-loops) You'll find a corresponding way of writing a for loop in pretty much any (imperative) programming language. You'll notice, it is very explicit in the way it works. E.g. you could change the break-condition i < array.length to something else (e.g. i < array.length-1 for skipping the last position), or the step i++ (e.g. to i+=2), or start at a different index (e.g. let i = 5). You can iterate backwards instead of forwards through the array, if you want. Pretty much anything you can do in another for loop, you can do in this kind as well, if you know how.

Inside the brackets {...} you can then use i as a key to access the arrays values

Now this is all very powerful and nice, but it gets cumbersome to write every time, especially if in most of the cases you just want to iterate over an array. But luckily we have for-in:

For-in will retrieve you all the keys you have set yourself. With an array, you can use that to achieve the same result as above using

for(let i in array) {...}

Note however, that for-in is not only gonna give you the number keys from an array. It is also gonna work on other keys you have set yourself on any object:

let object = {
    key1 : 'value',
    key2 : 'value'
}

for(let i in object) {
    console.log(i)
}

will log out 'key1' and 'key2' (yes, the keys as well are strings here).

For a bit more precise description of what keys exactly it will give you, have a look at the link below.

When would you use for-in? Whenever you want to call some code for each element of an array / (almost) each property of an object once. E.g. when you want to increment all values in an array by 1. When not to use for-in? Don't use it if you need more granular control over the order you traverse the array in, or you don't want to hit all elements of the array, but only every second/third.

For an excellent resource on for-in loops I recommend Mozilla Developer Network

So, what are for-of loops then?

For-of loops are syntactically (i.e. the way you write them) very similar to for-in loops:

for(let v of array) {...}

However, for one, they are only going to work on so-called iterable objects (arrays are iterable). Second, you only get the values. They are no longer going to give you any keys!

let array = ['a', 'b', 'c']
for(let v of array) {
    console.log(v)
}

logs 'a', 'b' and 'c'. You won't know anymore, what keys these values had!

So, when to use these? Every time you just need the values and don't care about the keys. E.g. if you just want to print the values. When not to use them? If you want to swap elements of an array, if you want to reverse order. You can't even increment the values by 1 and store them back into the array, because for that, you would need to know their corresponding key.

For more information on for-in loops as well as what iterable actually means, again, I recommend the MDN

The only key differences that you'll have to consider would be

  • Say you want to start your loop from a specific index, you can do that with your traditional for loop but not using for...of.

  • You can't access indices of your array elements natively. You'll need to go for a workaround to achieve this.

      //Cannot access indices
      for(const num of [11,22,33,44,55]){
         console.log(num);
      }
    
    
      //Workaround
      for(const [index, num] of [11,22,33,44,55].entries()){
         console.log(num, index);
      }
    
发布评论

评论列表(0)

  1. 暂无评论