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 statementwhile语句
- 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:
您刚刚开始编程之旅吗? 以下是一些您可能也会感兴趣的文章:
Is a coding bootcamp something for you?
编码训练营适合您吗?
Is career change really possible?
职业转变真的有可能吗?
Why Ruby is a great language to start programming with
为什么Ruby是一门很好的编程语言
翻译自: https://www.freecodecamp.org/news/javascript-iterators-17ab32c3cae7/
javascript迭代器
相关文章:

knockout学习笔记目录
关于knockout学习系列的文章已经写完,这里主要是做个总结,并且将目录罗列出来,方便查看。欢迎各位大神拍砖和讨论。 总结 kncokout是一个轻量级的UI类库,通过MVVM模式使前端的UI简单话,减少javascript代码的编写。通常…

ant Design Pro 登录状态管理
未登录自动跳转到登录页面,登录成功不跳转回登录页面的实现代码调用流程。 ant Design Pro 是一个企业中后台管理框架,开始做他,第一个肯定是要做登录,下面来看一下它是怎么登录的。 先看路由配置 Authorized.jsx代码࿱…

初级java开发学习路线_成为初级全栈Web开发人员的10分钟路线图
初级java开发学习路线So you have started your journey into the world of web development. But what do you learn first? The Internet is overloaded with a wealth of information about the millions of different technologies that a web developer can know.因此&am…

国外物联网平台初探(四):Ayla Networks
定位 Ayla企业软件解决方案为全球部署互联产品提供强大的工具 功能 Ayla的IoT平台包含3个主要组成部分: (1) Ayla嵌入式代理Ayla Embedded Agents (2) Ayla云服务Ayla Cloud Services (3) Ayla应用库Ayla Application Libraries 设备 开发者使用任何微控制器、操作系…

《英语语法新思维初级教程》学习笔记(一)名词短语
参考资料: 1. 《英语语法新思维初级教程》 ▶ 知识点 ▼ 英语是“固定词序语言(a fixed-word-order language)”。 ▼ 语言的构造级别分五个层次:1. 词(word);2. 短语(phase…

根据数组中对象的属性值排序倒叙
数组中对象的属性值排序倒叙demo function compare(e) {return function (a, b) {var value1 a[e];var value2 b[e];return parseInt(value1) - parseInt(value2);} } var arr[{a:2},{a:3},{a:1}];var arr2 arr.sort(compare(time)).reverse();console.log(arr2) //[{a:3}…

!! javascript_产量! 产量! 生成器如何在JavaScript中工作。
!! javascriptby Ashay Mandwarya ?️??由Ashay Mandwarya提供吗? 产量! 产量! 生成器如何在JavaScript中工作。 (Yield! Yield! How Generators work in JavaScript.) If the title doesn’t already give a hint, we will be discussin…

ACM 竞赛高校联盟 练习赛 第二场 BC
B. 题解: 枚举约数即可,判断n个数能否填约数的整数倍 #include <iostream> #include <cstring> #include <cstdio> using namespace std; typedef long long LL; int main(){LL T, n, m;cin>>T;while(T--){cin>>n>>…

在一个数组中查找两个重复出现的数字
题目如下:现有一个数组长度为n1,里面存放有1到n-2,顺序不定,其中有两个数字出现了两次,现在要找出那两个数字。 例子A{2, 3, 1, 4, 5, 2, 4}, 这个数组长度为7,存放了1到5,但2和4出现…

React 组件生命周期
组件的生命周期可分成三个状态: Mounting:已插入真实 DOMUpdating:正在被重新渲染Unmounting:已移出真实 DOM 生命周期的方法有: componentWillMount 在渲染前调用,在客户端也在服务端。 componentDidMount : 在第一…

银行软件开发实习生_如何找到学生的软件开发人员实习生
银行软件开发实习生by Grazietta Hof由Grazietta Hof 如何找到学生的软件开发人员实习生 (How to find a Software Developer Internship as a student) Side note: Although this article is directed at students (because I am one so I can easily relate), I’m sure a l…

MAC OS X El CAPITAN 搭建SPRING MVC (1)- 目录、包名、创建web.xml
一、 下载STS(Spring Tool Suite) 官方地址:http://spring.io/tools/sts 下载spring tool suite for mac 最新版本。这个IDE是很不错的,其中spring插件已经配置好了。下载解压缩(一定要英文目录下)…

iOS小知识点记录
1>UITextField实现leftView: self.inputTextField [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 200, 25)];self.inputTextField.delegate self;self.inputTextField.font [UIFont systemFontOfSize:15];self.inputTextField.placeholder " 想说点什么?…

Ant Design Pro 网络请求,视图绑定model并且渲染到页面 umi-request
封装网络请求,在service中新建接口,在model调用service,在视图绑定model并且得到网络请求的回调函数,获取网络请求的数据渲染到页面。 网络请求数据走向; 1.在utils/request.js 封装网络请求; /*** request 网络请求工具* 更详细的 api 文档: https://github.com/umijs…

2019机器学习比赛_2019顶尖的机器学习课程
2019机器学习比赛With strong roots in statistics, Machine Learning is becoming one of the most interesting and fast-paced computer science fields to work in. There’s an endless supply of industries and applications machine learning can be applied to to mak…

HTML5 canvas画图
HTML5 canvas画图 HTML5 <canvas> 标签用于绘制图像(通过脚本,通常是 JavaScript)。不过,<canvas> 元素本身并没有绘制能力(它仅仅是图形的容器) - 您必须使用脚本来完成实际的绘图任务。getCo…
排序算法7---快速排序算法
原理: 通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序的目的。 #include <stdio.h> #define MAXSIZE 9typedef stru…

dispatch callback ant design pro 网络请求回调函数
index.jsx 代码解析:在组件初次渲染时调用 model 中 命名空间为 a_models 的 getData 网络请求,传了一个patload 参数和 callback 回调函数过去,然后通过 this.setState ()更新视图的 state。 import { Form, Tabs,Affix, Button,Input,Table } from antd; import Re…

bigquery使用教程_如何使用Python和Google BigQuery构建机器人以自动执行您的笨拙任务...
bigquery使用教程Do you have repetitive tasks? Something that you do regularly, every week or even every day? Reporting might be one of your weekly or daily tasks. You query or ask for the data, and do some visualizations, then give it to your boss. What …

5S后返回首页
1 <!DOCTYPE html>2 <html>3 <head>4 <title>5S后返回首页</title> 5 <meta http-equiv"Content-Type" content"text/html; charsetgkb"/> 6 </head>7 <body>8 <h2>操作成功</h2>…
TypeScript 1
TypeScript 的由来 TypeScript 是 JavaScript 的一个超集,支持 ECMAScript 6 标准。 TypeScript 由微软开发的自由和开源的编程语言。 TypeScript 设计目标是开发大型应用,它可以编译成纯 JavaScript,编译出来的 JavaScript 可以运行在任何…

大龄屌丝自学笔记--Java零基础到菜鸟--028
泛型,for循环增强应用,静态导入,可变参数,asList() 1、泛型 约束了数据类型,格式为 <数据类型>,如:ArrayList<int> aListnew ArrayList<int>(); 泛型通配符:<?…

c# typescript_在任何IDE中从C#,Java或Python代码获取TypeScript接口的简单方法
c# typescriptby Leonardo Carreiro莱昂纳多卡雷罗(Leonardo Carreiro) 在任何IDE中从C#,Java或Python代码获取TypeScript接口的简单方法 (The easy way to get TypeScript interfaces from C#, Java, or Python code in any IDE) Who has never experi…

js里的document对象大全(DOM操作)
什么是DOM document object model 的简称,意思为文档对象模型。主要用来对文档中的html节点进行操作。 Dom的操作简单示例: <div id"t1"><div><input type"file" /> <input type"button" value"…

【制作镜像】BCEC制作镜像
如要制作的新镜像已存在标准版本镜像,即linux发行版本相同(此处指CentOS6.5 64位),可利用BCEC制作。 在BCEC创建centos6.5系统的可联外网的虚机,ssh到此虚机,用yum方式安装所需的功能: yum&…

Ant Design Pro 组件事件绑定 Input onChange
Input 组件的 onChange 事件绑定语法 render() {this.shop_change e > {const { value } e.target;console.log(shop_change,value)};return (<Input placeholder"" onChange{this.shop_change}></Input>)}

软件访问转向本地_我是如何从完整的初学者转向软件开发人员的,以及如何做到的...
软件访问转向本地by Madison Kanna麦迪逊卡纳(Madison Kanna) 我是如何从完整的初学者转向软件开发人员的,以及如何做到的 (How I went from complete beginner to software developer — and how you can too) Two years ago, I was right where you are today.两…

.NET笔试题集(五)
转载于:http://www.cnblogs.com/ForEvErNoME/archive/2012/09/15/2684938.html 1.什么是受管制的代码? 答:unsafe:非托管代码。不经过CLR运行。 2.net Remoting 的工作原理是什么? 答:服务器端向客户端发送…

devServer proxy跨域 设置代理 proxy
概念 什么是同源策略 同源策略是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。 所谓同源是指…

转帖 开源游戏服务器调研
汇总贴 2013年优秀的开源引擎与开源游戏项目 http://mobile.51cto.com/aengine-431122.htm http://www.oschina.net/search?scopeproject&q%E6%89%8B%E6%B8%B8 当前的几种开源游戏服务端介绍 http://www.oschina.net/question/1986738_224669 用户贴,使用过后…