javascript迭代器_JavaScript迭代器概述

javascript迭代器

by Joanna Gaudyn

乔安娜·高登(Joanna Gaudyn)

JavaScript迭代器概述 (An overview of JavaScript iterators)

for,for…in和for…of循环之间的区别 (The difference between for, for…in and for…of loops)

Iteration might be one of the most commonly used operations in programming. It is taking a set of items and performing a given operation on each and every one of them in a sequence. Loops allow for a quick and easy way to do something repeatedly.

迭代可能是编程中最常用的操作之一。 它正在处理一组项目,并按顺序对每个项目执行给定的操作。 循环允许快速简便地重复执行某项操作。

In JavaScript, different looping mechanisms let you define the beginning and end of a loop in different ways. There’s no easy answer to which of the mechanisms is the best, as different situations call for different approaches, meaning that your needs can be more easily served by one type of loop over the others.

在JavaScript中,不同的循环机制可让您以不同的方式定义循环的开始和结束。 对于哪种机制最好,没有简单的答案,因为不同的情况要求使用不同的方法,这意味着通过一种类型的循环可以比其他方式更轻松地满足您的需求。

Here’s what you can use to loop in JavaScript:

这是可用于在JavaScript中循环的内容

  • do…while statement

    做…当声明
  • while statement

    while语句
  • labeled statement

    标记声明
  • break statement

    中断声明
  • continue statement

    继续声明
  • for statement

    声明
  • for…in statement

    为...在声明中
  • for…of statement

    对于……的陈述

Let’s have a closer look at the last 3. They tend to be quite confusing when you start working with JavaScript, as the names don’t really make it easier to memorize the mechanics behind them. I hope a couple of examples will make things fall in place if you still are a little shaky on the concepts.

让我们仔细看一下最后3个。当您开始使用JavaScript时,它们往往会造成混乱,因为名称实际上并不能使记住它们背后的机制变得更加容易。 我希望如果您对概念仍然有些犹豫,可以使用一些示例使事情落到实处。

“ for”循环 (The ‘for’ loop)

The for loop is the most common type of looping and you might have stumbled upon it in other programming languages as well, so let’s just have a quick refresher.

for循环是最常见的循环类型,您可能在其他编程语言中也偶然发现过它,因此让我们快速回顾一下。

Here is the basic syntax:

这是基本语法:

for ([initialExpression]; [exit condition]; [incrementExpression]) {
  do something;
}

Let’s take an example:

让我们举个例子:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

Prints:

版画

0

0

1

1个

2

2

3

3

4

4

5

5

6

6

7

7

8

8

So what really happens here? A for loop repeats until a specified condition evaluates to false. In our case, we are starting a counter (variable i) at 0, print a number from our numbers array which lives at the i index of the array, and finally increment the counter. We also declare that our loop is supposed to break when the counter is no longer smaller than the size of the array (numbers.length).

那么这里到底发生了什么? 重复for循环,直到指定条件的计算结果为false。 在我们的例子中,我们将在0处启动一个计数器(变量i ),从我们的numbers数组中打印一个数字,该numbers位于该数组的i索引中,最后递增该计数器。 我们还声明,当计数器的大小不再小于数组的大小( numbers.length )时,我们的循环应该中断。

The biggest drawbacks of a for loop is having to keep track of a counter and exit condition. The syntax is also not very straightforward, and to understand what’s happening you really just need to memorize what each part of the code stands for. Even though a for loop can be a practical solution to loop through an array, there’s often neater ways to do it.

for循环的最大缺点是必须跟踪计数器和退出条件。 语法也不是很简单,要真正了解所发生的事情,您只需要记住代码各部分所代表的含义即可。 即使for循环可能是遍历数组的实用解决方案,但通常也有更巧妙的方法。

for…in循环 (The for…in loop)

The for ... in loop eliminates the two major weaknesses of the for loop. There’s no need to think of a counter or an exit condition.

for ... in循环消除了for循环的两个主要缺点。 无需考虑计数器或退出条件。

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in numbers) {
  console.log(numbers[index]);
}

Prints:

印刷品:

0

0

1

1个

2

2

3

3

4

4

5

5

6

6

7

7

8

8

The main disadvantage of this solution is that we still need to use an index to access the elements of the array.

该解决方案的主要缺点是我们仍然需要使用索引来访问数组的元素。

Another thing that can be problematic is that for ... in loops loop over all enumerable properties. What does it mean in practice? If you need to add an additional method to your object (in our case: array), this method will also appear in your loop.

可能引起问题的另一件事是for ... in循环遍历所有可枚举的属性。 实际上是什么意思? 如果您需要向对象中添加其他方法(在我们的示例中为数组),则该方法也将出现在循环中。

Have a look at this example:

看一下这个例子:

Array.prototype.decimalfy = function() {
  for (let i = 0; i < this.length; i++) {
    this[i] = this[i].toFixed(4);
  }
};

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in numbers) {
  console.log(numbers[index]);
}

Prints:

印刷品:

0

0

1

1个

2

2

3

3

4

4

5

5

6

6

7

7

8

8

9

9

function() {

function(){

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

for(让i = 0; i <this.length; i ++){

this[i] = this[i].toFixed(2);

this [i] = this [i] .toFixed(2);

}

}

I guess you’ll agree that it’s not exactly what we were after. When looping over arrays, try to stay away from the for ... in loops to avoid unexpected surprises.

我想您会同意这与我们追求的不完全相同。 遍历数组时,请尽量远离for ... in循环,以避免意外的意外。

for…循环 (The for … of loop)

The for…of loop is the newest addition to the family of for loops in JavaScript.

for…of循环是JavaScript中for循环家族的最新成员。

It combines the strengths of the for loop and the for ... in loop, allowing you to loop over any type of data type that is iterable (= follows the iterable protocol), such as string, array, set or map. Note that object ( {}) is not iterable by default.

它结合了for循环和for ... in循环的优点,使您可以循环访问任何可迭代的数据类型(=遵循可迭代协议 ),例如字符串,数组,集合或映射。 请注意,默认情况下,对象( {} )是不可迭代的。

The syntax of a for ... of loop is almost the same as of a for ... in loop:

for ... of循环的语法与for ... in循环的语法几乎相同:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const number of numbers) {
  console.log(number);
}

Prints:

印刷品:

0

0

1

1个

2

2

3

3

4

4

5

5

6

6

7

7

8

8

One big advantage is that we no longer need an index and can access elements or our array directly. It makes the for ... of loop the most compact of the whole family of for loops.

一大优点是我们不再需要索引,而可以直接访问元素或数组。 它使for ... of循环成为整个for循环系列中最紧凑的。

In addition, the for ... of loop mechanism allows for a loop break, depending on your condition. Have a look at this example:

此外, for ... of循环机制允许循环中断,具体取决于您的情况。 看一下这个例子:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const number of numbers) {
  if (number % 2 !== 0) {
    continue;
  }
  console.log(number);
}

Prints:

印刷品:

0

0

2

2

4

4

6

6

Furthermore, adding new methods to objects doesn’t affect the for ... of loop:

此外,向对象添加新方法不会影响for ... of循环:

Array.prototype.decimalfy = function() {
  for (i = 0; i < this.length; i++) {
    this[i] = this[i].toFixed(4);
  }
};
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const number of numbers) {
  console.log(number);
}

Prints:

印刷品:

0

0

1

1个

2

2

3

3

4

4

5

5

6

6

7

7

8

8

This makes the for ... of loop the most potent of all!

这使for ... of循环最有效!

旁注:forEach循环 (Side note: the forEach loop)

What might also be worth mentioning is a forEach loop. Note, however, that forEach() is an array method and therefore cannot be used on other JavaScript objects. This method can be useful if your case meets two conditions: you want to loop over an array and you don’t need to stop the loop before the end of that array:

还可能值得一提的是forEach循环。 但是请注意, forEach()是数组方法,因此不能在其他JavaScript对象上使用。 如果您的情况满足两个条件,则此方法很有用:您要遍历数组,而无需在该数组结束之前停止循环:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

numbers.forEach(function(number) {
  console.log(number);
});

Prints:

印刷品:

0

0

1

1个

2

2

3

3

4

4

5

5

6

6

7

7

8

8

I hope these examples helped you wrap your head around all the different mechanics of iteration in JavaScript.

我希望这些示例可以帮助您将注意力集中在JavaScript的所有不同的迭代机制上。

Are you just starting your journey with programming? Here’s some articles that might interest you as well:

您刚刚开始编程之旅吗? 以下是一些您可能也会感兴趣的文章:

翻译自: https://www.freecodecamp.org/news/javascript-iterators-17ab32c3cae7/

javascript迭代器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值