es6 迭代器_揭秘ES6迭代器和迭代器

es6 迭代器

by Tiago Lopes Ferreira

由Tiago Lopes Ferreira

揭秘ES6迭代器和迭代器 (Demystifying ES6 Iterables & Iterators)

ES6 introduces a new way to interact with JavaScript data structures — iteration. Let’s demystify it.

ES6引入了一種與JavaScript數據結構進行交互的新方法- 迭代 。 讓我們揭開神秘面紗。

There are 2 core concepts:

有兩個核心概念:

  • Iterable — described by a data structure that provides a way to expose its data to the public. This is done by implementing a method whose key is Symbol.iterator. Symbol.iterator is a factory of iterators.

    可迭代 -由數據結構描述,該數據結構提供了將其數據公開給公眾的方式。 這是通過實現鍵為Symbol.iterator的方法來Symbol.iteratorSymbol.iterator是迭代器的工廠。

  • Iterator — described by a structure that contains a pointer to the next element in the iteration.

    迭代器 -由包含指向迭代中下一個元素的指針的結構描述。

協議 (Protocol)

Both iterable and iterator follow a protocol that enables objects to be iterable:

可迭代和迭代器均遵循使對象可迭代的協議:

  • An interable must be an object with a function iterator whose key is Symbol.iterator.

    一個互操作對象必須是帶有函數迭代器的對象,該函數的鍵為Symbol.iterator

  • An iterator must be an object with a function named next that returns an object with the keys: value — the current item in the iteration; and donetrue if the iteration has finished, false otherwise.

    迭代器必須是具有next函數的對象,該函數返回具有以下鍵的對象: value —迭代中的當前項; 并done -如果迭代已完成,則為true ,否則為false

可重復性 (Iterability)

Iterability follows the idea of data sources and data consumers:

可迭代性遵循數據源數據使用者的思想:

  • data sources— are the place from where data consumers get their data. For instance, an Array such as [1,2,3] is a data source structure that holds the data through which a data consumer will iterate (e.g. 1, 2, and 3). More examples are String, Maps and Sets.

    數據源 -是數據使用者從中獲取數據的地方。 例如,諸如[1,2,3]類的Array是一種數據源結構,其中保存數據,數據使用者將通過該數據進行迭代(例如1, 2, and 3 )。 更多示例包括StringMapsSets

  • data consumers — are the what consume the data from data sources. For instance, the for-of loop is a data consumer able to iterate over an Array data source. More examples are the spread operator and Array.from.

    數據使用者 -消耗數據源中數據的對象。 例如, for-of循環是一個能夠遍歷Array數據源的數據使用者。 spread operatorArray.from是更多示例。

For a structure to be a data source, it needs to allow and say how its data should be consumed. This is done through iterators. Therefore, a data source needs to follow the iterator protocol described above.

為了使結構成為數據源 ,它需要允許并說出應如何使用其數據。 這是通過迭代器完成的。 因此, 數據源需要遵循上述迭代器協議。

However, it’s not practical for every data consumer to support all data sources, especially since JavaScript allows us to build our own data sources. So ES6 introduces the interface Iterable.

但是,每個數據使用者都不支持所有數據源是不切實際的,特別是因為JavaScript允許我們構建自己的數據源。 因此,ES6引入了Iterable接口

Data consumers consume the data from data sources through iterables.

數據使用者通過可迭代對象消耗數據源中的數據。

在實踐中 (In Practice)

Let’s see how this works on a defined data source — Array.

讓我們看看如何在定義的數據源Array

可迭代的數據源 (Iterable Data Sources)

We will use for-of to explore some of the data sources that implement the iterable protocol.

我們將使用for-of探索實現可迭代協議的一些數據源。

普通物體 (Plain Objects)

At this stage we need to say that plain objects are not iterable. Axel Rauschmayer does a great job explaining why on Exploring ES6.

在這一階段,我們需要說普通對象是不可迭代的。 Axel Rauschmayer出色地解釋了為什么要探索ES6 。

A brief explanation is that we can iterate over a JavaScript objects at two different levels:

一個簡短的解釋是,我們可以在兩個不同的級別上遍歷一個JavaScript對象:

  • program level — which means iterating over an object properties that represent it’s structure. For instance, Array.prototype.length, where length is related with the object’s structure and not it’s data.

    程序級別 –意味著遍歷代表其結構的對象屬性。 例如, Array.prototype.length ,其中length與對象的結構而不是數據有關。

  • data level — meaning iterating over a data structure and extracting its data. For instance, for our Array example, that would mean iterating over the array’s data. If array = [1,2,3,4], iterate over the values 1, 2, 3 and 4.

    數據級別 -意味著遍歷數據結構并提取其數據。 例如,對于我們的Array示例,這意味著迭代數組的數據。 如果array = [1,2,3,4] ,則迭代值1, 2, 3 and 4

However, bringing the concept of iteration into plain objects means mixing-up program and data structures — Axel

但是,將迭代的概念引入普通對象意味著混合程序和數據結構 -Axel

The problem with plain objects is everyones’ ability to create their own objects.

普通對象的問題是每個人都可以創建自己的對象。

In our Hugo’s example how would JavaScript distinguish between the data level, i.e. Hugo.fullName, and the program level, i.e. Hugo.toString()?

在我們的Hugo例子中,JavaScript如何區分數據級別(即Hugo.fullName )和程序級別(即Hugo.toString()

While it is possible to distinguish between the two levels of iteration on well-defined structures, such as Arrays, it is impossible to do so for any object.

雖然可以在定義良好的結構(例如Arrays上區分兩個迭代級別,但是對于任何對象都不可能做到這一點。

This is why we get iteration for free on Array (also on String, Map, and Set) but not on plain objects.

這就是為什么我們可以在Array (在StringMapSet )免費獲得迭代,而在普通對象上不能免費獲得迭代的原因。

We can, however, implement our own iterables.

但是,我們可以實現自己的可迭代對象。

實施可迭代 (Implement Iterables)

We can build our own iterables, although we usually use generators for that.

盡管我們通常為此使用生成器,但我們可以構建自己的可迭代對象。

In order to build our own iterable we need to follow the iteration protocol, which says:

為了構建自己的可迭代對象,我們需要遵循迭代協議,該協議指出:

  • An object becomes an iterable if it implements a function whose key is Symbol.iterator and returns an iterator.

    如果對象實現了鍵為Symbol.iterator的函數并返回iterator則該對象成為 iterator

  • The iterator itself is an object with a function called next inside it. next should return an object with two keys value and done. value contains the next element of the iteration and done a flag saying if the iteration has finished.

    iterator本身是一個對象,該對象內部具有一個稱為next的函數。 next應該有兩個鍵返回一個對象valuedonevalue包含迭代的下一個元素,并done了一個標志,指出迭代是否已完成。

(Example)

Our iterable implementation is very simple. We have followed the iterable protocol and on each iteration the for-of loop will ask the iterator for the next element.

我們的迭代實現非常簡單。 我們遵循了可迭代的協議,并且在每次迭代中, for-of循環都會向迭代器詢問next元素。

Our iterator will return on next an object containing the following by iteration:

next ,我們的迭代器將通過迭代返回一個包含以下內容的對象:

Please note that we switch the order of the our properties next and done for convenience. Having next first, it would break the implementation since we will first pop an element and then count the elements.

請注意,為了方便起見,我們next切換屬性的順序并done 。 首先擁有next一個,這將破壞實現,因為我們將首先彈出一個元素,然后對元素進行計數。

It is useful to know that done is false by default, which means that we can ignore it when that’s the case. The same is true for value when done is true.

知道默認情況下donefalse的,這很有用,這意味著在這種情況下我們可以忽略它。 當donetrue時, value也是true

We will see that in a minute.

我們將在一分鐘內看到。

作為迭代器的迭代器 (Iterator as an Iterable)

We could build our iterator as an iterable.

我們可以將迭代器構建為可迭代的。

Please note that this is the pattern followed by ES6 built-in iterators.

請注意,這是ES6內置迭代器遵循的模式。

Why is this a useful?

為什么這很有用?

Although for-of only works with iterables, not with iterators, being the same means that we can pause the execution of for-of and continue afterwords.

盡管for-of僅適用于可迭代對象,不適用于迭代器,但相同意味著我們可以暫停for-of的執行并繼續執行后記。

回程和擲球 (Return and Throw)

There are two optional iterator methods that we haven’t explore yet:

我們還沒有探討兩種可選的迭代器方法:

Return

返回

return gives the iterator the opportunity to clean up the house when it breaks unexpectedly. When we call return on an iterator we are specifying that we don’t plan to call next anymore.

return給迭代器一個機會,當它意外崩潰時,它可以清理房子。 當我們在迭代器上調用return時,我們指定不打算再調用next了。

Throw

throw is only applied to generators. We will see that when we play with generators.

throw僅應用于生成器。 當我們使用生成器時,我們會看到這一點。

結論 (Conclusion)

ES6 brings iteration as a new way to iterate over JavaScript data structures.

ES6將迭代作為迭代JavaScript數據結構的新方法。

For iteration to be possible there are data producers, who contain the data, and data consumers, who take that data.

為了使迭代成為可能,需要有包含數據的數據生產者和獲取數據的數據使用者

In order for this combination to work smoothly iteration is defined by a protocol, which says:

為了使此組合順利運行,協議定義了迭代,該協議表示:

  • An iterable is an object that implements a function whose key is Symbol.iterator and returns an iterator.

    一個iterable是一個對象,該對象實現一個鍵為Symbol.iterator并返回iterator

  • An iterator is an object with a function called next inside it. next is an object with two keys value and done. value contains the next element of the iteration and done a flag saying if the iteration has finished.

    iterator是一個對象,其內部具有一個稱為next的函數。 next是兩個鍵對象valuedonevalue包含迭代的下一個元素,并done了一個標志,指出迭代是否已完成。

Plain objects are not iterable since there’s no easy way to distinguish between program and data level iteration.

普通對象是不可iterable因為沒有簡單的方法可以區分程序和數據級別的迭代。

That’s why ES6 offers a way to build our own iterators by following the iterator protocol.

這就是為什么ES6提供一種通過遵循iterator協議來構建自己的迭代iterator

謝謝 ? (Thanks to ?)

  • Axel Rauschmayer for his Exploring ES6 — Iteration

    Axel Rauschmayer的探索性ES6-迭代

  • Nicolás Bevacqua for his PonyFoo — ES6 Iterators in Depth

    尼古拉斯·貝瓦夸 ( NicolásBevacqua)的PonyFoo-深入研究ES6迭代器

  • To all The Simpsons fans

    致所有《辛普森一家》粉絲

Be sure to check out my other articles on ES6

請務必查看我有關ES6的其他文章

Let’s explore ES6 GeneratorsGenerators are an implementation of iterables.medium.freecodecamp.com

讓我們探索一下ES6生成 生成 器是可迭代的實現。 medium.freecodecamp.com

翻譯自: https://www.freecodecamp.org/news/demystifying-es6-iterables-iterators-4bdd0b084082/

es6 迭代器

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395270.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395270.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395270.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

JS之this與語句分號問題v(**V**)v

1 <script >2 //this知識 單詞知識&#xff1a;property&#xff1a;屬性 prototype&#xff1a;原型3 //*Q&#xff1a;什么是this&#xff1f;4 //*A&#xff1a;所有函數內部都有一個this&#xff0c;任何函數本質上都是通過某個對象來調用的&#xff0c;…

計算機聯系函范文,致客戶聯絡函

致客戶聯絡函 相關內容:收到貴支部所發的“函調證明”通知&#xff0c;很高興我校畢業生xxx同學能成為貴支部的黨員發展對象&#xff0c;現對其在我校上學其間的表現證明如下&#xff1a;xxx&#xff0c;女&#xff0c;xxx年7月28日生&#xff0c;團員&#xff0c;XX年8月——X…

c語言堆棧基本代碼入棧出棧_c語言的簡單的進棧出棧

這個代碼運行時只能輸入4個以內的數有輸出4個以上就沒有輸出了求大神看看#include#include#defineStack_Size50typedefstructSeqstack{intelem[Stack_Size];inttop...這個代碼運行時只能輸入4個以內的數有輸出 4個以上就沒有輸出了 求大神看看 #include #include #define Stack…

P1401 城市(30分,正解網絡流)

題目描述 N(2<n<200)個城市&#xff0c;M(1<m<40000)條無向邊&#xff0c;你要找T(1<T<200)條從城市1到城市N的路&#xff0c;使得最長的邊的長度最小&#xff0c;邊不能重復用。 輸入輸出格式 輸入格式&#xff1a; 第1行三個整數N,M,T用空格隔開。 第2行到…

sqlserver游標概念與實例全面解說

引言 我們先不講游標的什么概念&#xff0c;步驟及語法&#xff0c;先來看一個例子&#xff1a; 表一 OriginSalary 表二 AddSalary 現在有2張表&#xff0c;一張是OriginSalary表--工資表&#xff0c;有三個字段0_ID 員工…

為什么Docker對初創企業有意義

by Charly Vega查理維加(Charly Vega) 為什么Docker對初創企業有意義 (Why Docker makes sense for startups) Docker is becoming the standard to develop and run containerized applications.Docker正在成為開發和運行容器化應用程序的標準。 Long ago, this piece of te…

MyEclipse中Maven Web項目部署路徑設置

轉載于:https://www.cnblogs.com/langzichanglu/p/10336805.html

小米電視聯網后顯示無法解析小米電視服務器,小米電視連上無線不能上網怎么回事?教你解決辦法...

原標題&#xff1a;小米電視連上無線不能上網怎么回事&#xff1f;教你解決辦法互聯網電視憑借在線觀看影視劇這個獨有的優勢受到越來越多家庭的喜愛。特別是配置不俗的小米電視&#xff0c;然而隨之而來的的問題也讓很多用戶頭疼&#xff0c;比如家里的小米電視突然上不了網了…

配置Server Side TAF

實驗環境&#xff1a;Oracle 11.2.0.4 RAC1.為設置TAF在RAC集群上新建服務2.啟動server_taf服務3.檢查確認服務正在運行4.找到剛創建服務的service_id5.根據service_id審查服務的信息6.給服務添加server side failover參數7.再次審查服務可以看到Method, Type和Retries值8.檢查…

fgets阻塞 stdin 退出_來自stdin問題的fgets[c]

我試過你的代碼,但無法重現問題。以下代碼的工作方式正是您所期望的,它會提示您輸入名稱,等待您鍵入名稱,然后提示您輸入地址,等等。我想知道你是否不需要在提示輸入更多信息之前閱讀stdin并清空它?typedef struct {char* name;char* address;}employeeRecord;int readrecord(…

2016.08.19

轉載于:https://www.cnblogs.com/hiramlee0534/p/5789453.html

服務器上運行arp,服務器ARP病毒的特征及防護說明

服務器ARP病毒的特征及防護說明更新時間&#xff1a;2008年01月29日 15:50:33 作者&#xff1a;服務器ARP病毒的特征及防護說明近期有些用戶反映服務器上所有網站被插入了病毒代碼,但是這些病毒代碼在服務器的源文件上并不能找到,因此,網管想清理病毒也無從下手,這是什么原因…

使用React Native進行氣泡動畫

by Narendra N Shetty由納倫德拉N謝蒂(Narendra N Shetty) 使用React Native進行氣泡動畫 (Bubble animation with React Native) 使用Animated和PanResponder構建React Native應用程序時獲得的經驗教訓 (Lessons learned while building a React Native App using Animated a…

Machine Learning from Start to Finish with Scikit-Learn

2019獨角獸企業重金招聘Python工程師標準>>> Machine Learning from Start to Finish with Scikit-Learn This notebook covers the basic Machine Learning process in Python step-by-step. Go from raw data to at least 78% accuracy on the Titanic Survivors …

Excel 宏編碼實現,指定列的字符串截取

1、打開Excel憑證&#xff0c;啟用宏&#xff0c;ALTF11 或 菜單“視圖”-"宏-查看宏" Sub 分割字符串1() Dim i As Integer Dim b() As String Dim length 用length表示數組的長度 Dim sublength Dim bb() As String 篩選日期 2 點 For i 2 To 20000 b() Split(Ce…

mysql for update 鎖_MySql FOR UPDATE 鎖的一點問題……

問題描述假設一個情況&#xff0c;這里只是假設&#xff0c;真實的情況可能不會這樣設計&#xff0c;但是假如真的發生了....鐵老大有一張這樣的ticket表&#xff0c;用來存放北京到上海的票。iduidstart_addrend_addrbook_time11300009860上海北京1386666032120上海北京30上海…

服務器機房新風系統,某機房新風系統設計方案參考

《某機房新風系統設計方案參考》由會員分享&#xff0c;可在線閱讀&#xff0c;更多相關《某機房新風系統設計方案參考(3頁珍藏版)》請在人人文庫網上搜索。1、某機房新風系統設計方案參考根據以上要求并結合中華人民共和國電子計算機機房的設計規范&#xff0c;為保證機房正壓…

css 畫三角形

CSS三角形繪制方法#triangle-up {width: 0;height: 0;border-left: 50px solid transparent;border-right: 50px solid transparent;border-bottom: 100px solid red;}#triangle-down {width: 0;height: 0;border-left: 50px solid transparent;border-right: 50px solid trans…

面試官面試前端_如何面試面試官

面試官面試前端by Aline Lerner通過艾琳勒納(Aline Lerner) 如何面試面試官 (How to interview your interviewers) For the last few semesters, I’ve had the distinct pleasure of guest-lecturing MIT’s required technical communication class for computer science m…

shell 字符串分割

語法1: substring${string:start:len} string的下標從0開始&#xff0c;以start可是&#xff0c;截取len個字符&#xff0c;并賦值于substring 1 #!/bin/bash 2 #substr${string:start:len} 3 str"123456789" 4 substr${str:3:3} 5 echo $substr 6 7 輸出&#xff1…