简体   繁体   English

For-Of 循环与 For 循环

[英]For-Of Loop vs. For Loop

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.如果还有任何其他示例/实例也很好。

A bit of backnowledge to explain your question:一些背景知识来解释你的问题:

In Javascript, Objects (among these are Arrays) store properties in key-value pairs.在 Javascript 中,对象(其中包括数组)以键值对的形式存储属性。 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. person是对象, name键和'Tom'对应的值。

Arrays use indices (ie numbers) as keys:数组使用索引(即数字)作为键:

array[5] = 10

Now, keep that in mind in the following explanation.现在,在下面的解释中记住这一点。

Let's start with the traditional for loop :让我们从传统的for 循环开始

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.这种迭代数组的方式是最古老的(只要您不使用 while 循环)您会发现在几乎任何(命令式)编程语言中编写 for 循环的相应方式。 You'll notice, it is very explicit in the way it works.您会注意到,它的工作方式非常明确。 Eg you could change the break-condition i < array.length to something else (eg i < array.length-1 for skipping the last position), or the step i++ (eg to i+=2 ), or start at a different index (eg let i = 5 ).例如,您可以将中断条件i < array.length更改为其他内容(例如, i < array.length-1用于跳过最后一个位置)或步骤i++ (例如更改为i+=2 ),或者从不同的索引开始(例如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.几乎任何你可以在另一个 for 循环中做的事情,你也可以在这种循环中做,如果你知道怎么做的话。

Inside the brackets {...} you can then use i as a key to access the arrays values在方括号{...}您可以使用i作为访问数组

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:

For-in will retrieve you all the keys you have set yourself. For-in将检索您自己设置的所有密钥 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.但是请注意,for-in 不仅会为您提供数组中的数字键。 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).将注销'key1''key2' (是的,这里的键也是字符串)。

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?你什么时候使用 for-in? Whenever you want to call some code for each element of an array / (almost) each property of an object once.每当您想为数组的每个元素/(几乎)对象的每个属性调用一些代码时。 Eg when you want to increment all values in an array by 1. When not to use for-in?例如,当您想将数组中的所有值都加 1 时。何时不使用 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对于 for-in 循环的优秀资源,我推荐Mozilla Developer Network

So, what are for-of loops then?那么,什么是 for-of 循​​环呢?

For-of loops are syntactically (ie the way you write them) very similar to for-in loops: For-of循环在语法上(即您编写它们的方式)与 for-in 循环非常相似:

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 .其次,你只能得到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' .记录'a''b''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.每次您只需要值而不关心键时。 Eg 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.您甚至不能将值加 1 并将它们存储回数组,因为为此,您需要知道它们对应的键。

For more information on for-in loops as well as what iterable actually means, again, I recommend the MDN有关 for-in 循环的更多信息以及 iterable 的实际含义,我再次推荐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 .假设您想从特定索引开始循环,您可以使用传统的 for 循环来执行此操作,但不使用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); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM