(I) The principle of native iterator
// The native iterator principle
function createIterator(items) {
var i = 0;
return {
next: function () {
var done = i >= items.length;
varval = ! done ? items[i++] :undefined;
return {
done: done,
value: val
}
}
}
}
Copy the code
(2) A for-of explanation
-
Iterator for iterating is obj[symbol. iterator]
-
Those that have this property can be traversed by for-of
- An array of
- Set
- Map
- Class array (for example arguments property)
- string
- The Generator object
-
Implement a for-of function yourself
function forOf(obj, cb) {
let iterable, result;
// If the Symbol. Iterator attribute type is not function, an error is thrown
if (typeof obj[Symbol.iterator] ! = ="function") {
throw new TypeError(result + 'is not iterable');
}
iterable = obj[Symbol.iterator]()
result = iterable.next();
while (!result.done) {
cb(result.value)
result = iterable.next();
}
}
// Start calling your forOf
forOf([1.2.3].(item) = > {
console.log(item);/ / 1, 2, 3
})
Copy the code
-
Adds attributes to arrays that can be traversed for-of
arr.name = 'e';
Iterator attribute is added to the array. This attribute does not go to the Symbol. Iterator attribute
Array.prototype.d = 'f'
Adding to the stereotype also does not allow for for traversal to this property
arr.push('d');
Properties added by the push method can be iterated with for of
(3) For in detail
-
Unlike for-of, which adds attributes with prototypes and arr.name = ‘e’, for-in can iterate over attributes that are added in this way, as can push, of course
-
Iterate through the order of results with for-in
function Foo() {
this[100] = 'test-100'
this[1] = 'test-1'
this['b'] = 'test-b'
this[50] = 'test-50'
this[9] = 'test-9'
this[8] = 'test-8'
this[3] = 'test-3'
this[5] = 'test-5'
this['A'] = 'test-A'
this['C'] = 'test-C'
}
let bar = new Foo();
for (let key in bar) {
console.log(`index:${key} value:${bar[key]} `);
}
// The order of traversal is as follows:
// index:1 value:test-1
// index:3 value:test-3
// index:5 value:test-5
// index:8 value:test-8
// index:9 value:test-9
// index:50 value:test-50
// index:100 value:test-100
// index:b value:test-b
// index:A value:test-A
// index:C value:test-C
Copy the code
We can also see that the for in traversal returns the key name, not the key value
(4) Summary
The for – in characteristics
- The loop returns the key name of the data structure
- The traversal array returns the index of the array
- You can iterate over not only existing values, but also keys on the prototype, as well as manually added keys
- In special cases, the order of traversal is not based on the attributes of the object
For characteristics of
- Cannot traverse objects (data structures without symbol. iterator attributes)
- Iterating over the array returns elements