In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what is for of and Iterator". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is for of and Iterator".
Start with a variable var arr = ['red', 'green', 'blue']
The above is an ordinary array. What should I do if I want to get every item of data about it?
This is not simple, just do a for loop, if you think the loop low, then have a forEach.
Ok, eat the barbecue code now.
/ / for loop
For (var iTuno Tinci {
Console.log (item)
});
/ / the result is brief
Ok, there's nothing wrong.
Then let's move on, please look at the following code. Given a string, what do I do if I want to output each character?
Var str='1234567890'
Are you kidding me? it's so simple that people laugh.
You can use for in, or you can use a for loop to deal with it as a class array.
Eat the barbecue code right away
/ / for in
For (var s in str) {
Console.log (str[ s]); / / s is the attribute name [key]
}
/ / convert to an array
For (var I = 0 * * I {
Console.log (val,key)
})
After reading so many simple questions here, I guess I can't sit still and I'm going to lift the table and leave. Please wait a moment and look down slowly.
Find a problem
Well, in the last few simple questions, our operation is to get each of their data.
Of course, there are many ways, and there are many ways to implement it, for loop, forEach,for in.
But have you found a problem, or if we look at it from a higher dimension, in fact, none of these methods can be universal, that is to say, the above collection data can not be obtained by using a unified traversal method.
Who said, can be unified ah, you can use forEach to traverse, the array and map itself support, the string I directly into the array on it.
Ok, there's nothing wrong with that.
But every time you have to convert, encapsulate, and possibly invade the prototype.
Is there a better, general-purpose way to make developers more comfortable and comfortable?
The answer is yes, es5 did not appear, upgrade to es6 will have.
NB's for of, pick it.
This way to uniformly traverse different data structures is es6's for of loop.
The for of loop is very similar to the old for loop. It's just a new grammar.
To quote a sentence from Boss Ruan's book, I believe it can be seen at a glance.
ES6 draws lessons from C++, Java, C # and Python, and introduces for...of cycle. As a unified method of traversing all data structures.
The key is unification, and the other is to take values directly, simplify the operation, and do not need to declare and maintain any variables and convert the data.
It turns out that for of is so awesome that you can handle the for cycle.
Why for of can have this ability can provide a unified way of data acquisition for different data structures.
Is for of really that powerful? what is the mechanism behind him?
For of is not really powerful, it's just a new syntax for ES6.
Not all objects can use for of, and only objects that implement the Iterator interface can use for of to traverse values.
So for of is just grammatical candy, and the real protagonist is Iterator.
What? Iterator.
The protagonist enters the stage-Iterator iterator
Iterator is an interface that aims to provide a unified data access mechanism for different data structures. It can also be understood that the Iterator interface is mainly for for of services and is consumed by for...of.
In fact, Iterator has been a feature of many back-end languages for many years, such as java, C++, C# and so on.
Since it is an interface, how should we implement this interface? What are the implementation rules?
Because there is no concept of interface in javascript language, we can understand that it is a special object-iterator object, and the method that returns this object is called iterator method.
First of all, he is an object, which has a next method, and each call to the next method returns a result value.
The resulting value is an object that contains two properties, value and done.
Value indicates the specific return value. Done is of Boolean type, indicating whether the collection is traversed or whether there is any data available later. If no data is available, true is returned, otherwise false is returned.
In addition, a pointer is maintained internally to point to the location of the current collection, and each time the next method is called, the pointer moves backward one position (which can be thought of as the index of an array).
Take a look at the code implementation
Function getIterator (list) {
Var I = 0
Return {
Next: function () {
Var done = (I > = list.length)
Var value =! done? List [iTunes +]: undefined
Return {
Done: done
Value: value
}
}
}
}
Var it = getIterator (['averse,' baked,'c'])
Console.log (it.next ()); / / {value: "a", done: false}
Console.log (it.next ()); / / {value: "b", done: false}
Console.log (it.next ()); / / {value: "c", done: false}
Console.log (it.next ()); / / "{value: undefined, done: true}"
Console.log (it.next ()); / / "{value: undefined, done: true}"
Console.log (it.next ()); / / "{value: undefined, done: true}"
The above code is a simulation implementation derived from the basic concept of iterators.
The getIterator method returns an object-the iterable object object has a next method. The value of the pointer I is saved inside the next method through a closure, and the value of the next method I is + 1. Then the data is taken from the array as value according to the value of I, and the value of done is determined by the index. When iDiff3, the maximum index of the array is exceeded and no available data is returned, so the done is true and traversal is complete. Iterable object
So far we have an overview of Iterator and how to create an iterator object. But what does he have to do with for of?
For of operation mechanism
When the for of is executed, the engine automatically calls the iterator method on the object during the loop, executes the next method of the iterator object in turn, and assigns the next return value to the variable in for of to get the specific value.
I think the above sentence contains an important message-"iterator methods on objects".
Implement iterable objects
Why is there an iterator method on the object?
ES6 states that as long as the Iterator interface is deployed on the properties of the object, in the form of adding a Symbol.iterator property to the object, this property points to an iterator method that returns a special object-the iterator object.
Objects that deploy this property and implement iterator methods are called iterable objects.
At this point, the object is iterable, that is, it can be traversed by for of.
Symbol.iterator, which is an expression that returns the iterator property of the Symbol object, which is a predefined special value of type Symbol.
For instance
Ordinary objects can not be ergodic by for of, direct consumption will report an error.
Var obj = {}
For (var k of obj) {
}
Obj is not an iterable object.
So let's make an object iterable and implement it in accordance with the protocol, that is, the rules.
Deploy the Symbol.iterator property on the iterableObj object, and then create an iterator method for it, the rules for which we have already talked about.
Var iterableObj = {
Items: [100200300]
[Symbol.iterator]: function () {
Var self=this
Var I = 0
Return {
Next: function () {
Var done = (I > = self.items.length)
Var value =! done? Self.items [iTunes +]: undefined
Return {
Done: done
Value: value
}
}
}
}
}
/ / traverse it
For (var item of iterableObj) {
Console.log (item); / / 100200300
}
As simple as that, the above object is iterable and can be consumed by for of.
Iterator native application scenario
Let's go back to the beginning of using for of to traverse strings, arrays, map, we did not deploy the Iterator interface for them, we can still use for of traversal.
This is because some objects in ES6 have deployed this interface by default, and you can use for of to traverse values without doing any processing.
You don't believe me? Oh, you are so difficult, I don't want you to say-letter, I want me to say-letter.
See if you can get their iterators.
Array
/ / array
Var arr= [100200300]
Var iteratorObj= arr [Symbol.iterator] (); / / get the iterator method and return the iterator object
Console.log (iteratorObj.next ())
Console.log (iteratorObj.next ())
Console.log (iteratorObj.next ())
Console.log (iteratorObj.next ())
String
Because the values of the string itself are ordered and have the feature of a class array that supports access through an index, the iterator interface is also deployed by default.
Var str='abc'
Var strIteratorObj = str [Symbol.iterator] (); / / get the iterator
Console.log (strIteratorObj.next ())
Console.log (strIteratorObj.next ())
Console.log (strIteratorObj.next ())
Console.log (strIteratorObj.next ())
Or just look at whether this property is deployed on the prototype.
Arguments class array
The arguments in the function is a class array, and it also supports for of because it also deploys the Iterator interface internally.
We all know that the object does not deploy this interface by default, so the property arguments is not on the prototype, but on the property of the object itself.
Function test () {
Var obj = arguments [Symbol.iterator] ()
Console.log (arguments.hasOwnProperty (Symbol.iterator))
Console.log (arguments)
Console.log (obj.next ())
}
Test (1, 2, 3)
To sum up, the objects that have deployed the Iterator interface by default mainly include arrays, strings, Set, Map, and array-like objects (such as arguments objects, DOM NodeList objects).
Code verification strategy, is a routine, do not say much.
Another function of Iterator
Apart from providing a unified way to access data for different data structures, has Iterator found any other functions?
That is, the data can be customized, because we can control the value value of the iterator at will.
For example, the array itself is iterable, and we can override its default iterator.
Var arr= [100200300]
For (var o of arr) {
Console.log (o)
}
The default output of the for of array is as follows
After our transformation
Var arr= [100200300]
Arr [Symbol.iterator] = function () {
Var self=this
Var I = 0
Return {
Next: function () {
Var done = (I > = self.length)
Var value =! done? Self [iTunes +]: undefined
Return {
Done: done
Value: value
}
}
}
}
For (var o of arr) {
Console.log (o)
} Why is the object not deployed by default
Objects may have a variety of properties, unlike array values that are ordered.
So when traversing, we have no idea how to prioritize them, so we need to implement them manually according to the situation.
Extended for of interrupt
We all know that ordinary for loops can be interrupted at any time, so can for of?
The answer is yes, the for of mechanism combines for and forEach.
In addition to the next method, the iterator has two optional methods, the return and the throw method.
If the for of loop exits early, the return method is called automatically. Note that the return method must have a return value, and the return value must be an object.
Ps: exit by throwing an exception, executing the return method first and then throwing an exception.
Var iterableObj = {
Items: [100200300]
[Symbol.iterator]: function () {
Var self=this
Var I = 0
Return {
Next: function () {
Var done = (I > = self.items.length)
Var value =! done? Self.items [iTunes +]: undefined
Return {
Done: done
Value: value
}
}
Return () {
Console.log ('exit early')
Return {/ / must return an object
Done:true
}
}
}
}
}
For (var item of iterableObj) {
Console.log (item)
If (item===200) {
Break
}
}
For (var item of iterableObj) {
Console.log (item)
Throw new Error ()
}
Ps:throw method aside here, this is not an opportunity for him to show his talents, see the following article.
Not only for of
Apart from the fact that the object's Iterator method is automatically called when for of executes, are there any other forms of syntax in ES6?
Deconstruction assignment
When you deconstruct an iterable object, the Symbol.iterator method is called by default.
/ / string
Var str='12345'
Var [aformab] = str
Console.log (afort b); / / 1 2
/ / map
Var map = new Map ()
Map.set ('I', 'front end')
Map.set ('yes', 'technology')
Map.set (who, jianghu)
Map.set ('author', 'zz_jesse')
Var [dline e] = map
Console.log (dline e)
/ / ["I", "front end"] ["Yes", "technology"]
....
Similarly, if you deconstruct a normal object, an error will be reported.
Because a normal object is not an iterable object.
Var [dline e] = {name:'zhang'}
Deconstruct the assignment from a custom iterable object.
Var iterableObj = {
Items: ['red', 'green', 'blue']
[Symbol.iterator]: function () {
Var self=this
Var I = 0
Return {
Next: function () {
Var done = (I > = self.items.length)
Var value =! done? Self.items [iTunes +]: undefined
Return {
Done: done
Value: value
}
}
}
}
}
Var [dline e] = iterableObj
Console.log (dline e); / / red and green
The value of the deconstructed assigned variable is the return value of the next method of the iterator object and is returned sequentially.
Extension operator
The execution of the extension operator (.) Its Symbol.iterator method is also called by default, which converts the current iterative object into an array.
/ / string
Var str='1234'
Console.log ([... str]); / / [1mem2jin3jin4] is converted to an array
/ / map object
Var map=new Map ([[1, 2], [3, 4]])
[... map] / / [[1,2], [3,4]
/ / set object
Var set=new Set ([1pm 2pm 3])
[... set] / / [1,2,3]
Generic objects cannot be converted to arrays.
Var obj= {name:'zhang'}
[.. obj] / / error report
As a data source
As a data source for some data, such as some api methods whose argument is to receive an array, their own iterators are called by default.
For example: Set, Map, Array.from, etc.
/ / to prove, overwrite the default iterator of an array
Var arr= [100200300]
Arr [Symbol.iterator] = function () {
Var self=this
Var I = 0
Return {
Next: function () {
Var done = (I > = self.length)
Var value =! done? Self [iTunes +]: undefined
Return {
Done: done
Value: value+' front-end technology jianghu'/ / pay attention here
}
}
}
}
For (var o of arr) {
Console.log (o)
}
/ / 100 front-end technology
/ / 200 Front-end technology
/ / 300 front-end technology
Overwritten completed
/ / generate set object
Var set = new Set (arr)
/ / call the Array.from method
Array.from (arr)
Yield* keyword
Yield* is followed by a traverable structure, and iterator functions are also called when executed.
Let foo = function* () {
Yield 1
Yield* [2,3,4]
Yield 5
}
Yield needs to be highlighted, which will be described in more detail in the next section.
Determine whether the object can be iterated
Since the rules of an iterable object must deploy the Symbol.iterator property on the object, we can basically use this attribute to determine whether the object is an iterable object, and then we can know whether the for of value can be used.
Function isIterable (object) {
Return typeof object [Symbol.iterator] = = "function"
}
Console.log (isIterable ('abcdefg')); / / true
Console.log (isIterable ([1,2,3])); / / true
Console.log (isIterable ("Hello")); / / true
Console.log (isIterable (new Map (); / / true
Console.log (isIterable (new Set (); / / true
Console.log (isIterable (new WeakMap (); / / false
Console.log (isIterable (new WeakSet (); / / false summary
The emergence of ES6 brings many new data structures, such as Map and Set, so for the convenience of data acquisition, a unified way of obtaining data, for of, is added. When for of executes, the engine automatically invokes the object's iterator to get the value.
Not all objects support this approach, but only if they implement the Iterator interface, which we call iterable objects.
The implementation of the iterator is based on the iterable protocol, and the iterator protocol can be implemented.
In addition to unifying data access, you can also customize the content of the data you get, whatever you need.
An iterator is a method that returns an iterator object.
An iterable object is an object that has the Iterator interface deployed and has the correct iterator methods.
Iterator is used in many places in ES6, so you can pay more attention to observation and think about it.
It's the end and the beginning.
At this point, we can customize the iterator according to the rules of the iterator, but the implementation process is a little complicated, after all, we need to maintain the internal pointer, there are a lot of logic processing, it is inevitable to make mistakes.
Is there a more elegant way to implement it?
Yes, that's the-Generator-generator.
Let obj = {
* [Symbol.iterator] () {
Yield 'hello'
Yield 'world'
}
}
For (let x of obj) {
Console.log (x)
}
/ / "hello"
/ / "world"
You can see that it is so concise that you can generate an iterator without too much code.
In addition to being a grammatical candy for generating iterators, it has more magical powers.
Let's take care of Iterator this time and Generator next time.
Thank you for your reading, the above is the content of "what is for of and Iterator". After the study of this article, I believe you have a deeper understanding of what is for of and Iterator, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.