-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
迭代器和生成器 #4
Comments
迭代器协议定义了一种标准的方式来产生一个有限或无限序列的值,并且当所有的值都已经被迭代后,就会有一个默认的返回值 迭代器iterator:在 JavaScript 中 迭代器是一个对象,它提供了一个next() 方法,用来返回序列中的下一项。这个方法返回包含两个属性done和 value的对象 简单迭代器实现:
创造一个同时满足迭代器协议和可迭代协议的对象: var obj = {
count: 1,
next() {
const done = this.count > 3
const value = this.count > 3 ? undefined : this.count++
return {value , done}
},
[Symbol.iterator]() { return this }
}
obj.next() // {value: 1, done: false}
obj.next() // {value: 2, done: false}
obj.next() // {value: 3, done: false}
obj.next() // {value: undefined, done: true}
obj.next() // {value: undefined, done: true}
...
for (let i of obj){console.log(i)} // 1 2 3 |
可迭代协议:允许 JavaScript 对象去定义或定制它们的迭代行为。 可迭代对象iterable:一个定义了迭代行为的对象,具有Symbol.iterator属性 一些内置类型都是内置的可迭代类型并且有默认的迭代行为, 比如 String, Array, TypedArray,arguments, Map and Set它们的原型对象都有一个 @@iterator 方法 自定义可迭代对象:
用于可迭代对象的语法:for-of,扩展运算符,yield*,解构赋值 接受可迭代对象的函数:Map([iterable]), WeakMap([iterable]), Set([iterable]) and WeakSet([iterable]) var myObj = {};
new Map([[1,"a"],[2,"b"],[3,"c"]]).get(2); // "b"
new WeakMap([[{},"a"],[myObj,"b"],[{},"c"]]).get(myObj); // "b"
new Set([1, 2, 3]).has(3); // true
new Set("123").has("2"); // true
new WeakSet(function*() {
yield {};
yield myObj;
yield {};
}()).has(myObj); // true 判断对象是否为可迭代对象的方法: typeof obj[Symbol.iterator] === 'function' |
生成器Generator:生成器Generator对象是由一个 generator function 返回的,并且它符合可迭代协议和迭代器协议。
function* gen() {
yield 1;
yield 2;
yield 3;
}
let g = gen(); // "Generator { }" Generator方法:
|
生成器对象到底是一个迭代器还是一个可迭代对象?生成器对象既是迭代器也是可迭代对象:一个良好的迭代即实现了迭代器协议,又实现了可迭代协议,方式就是可迭代协议返回的是自身 var aGeneratorObject = function*(){
yield 1;
yield 2;
yield 3;
}();
typeof aGeneratorObject.next;
// "function", because it has a next method, so it's an iterator
typeof aGeneratorObject[Symbol.iterator];
// "function", because it has an @@iterator method, so it's an iterable
aGeneratorObject[Symbol.iterator]() === aGeneratorObject;
// true, because its @@iterator method return its self (an iterator), so it's an well-formed iterable
[...aGeneratorObject];
// [1, 2, 3] |
1.避免开发者使用for循环还要控制index等,我们有了iterator就可以用for of。 |
for of 用于循环可迭代对象,包括有 Array, Set, Map, 字符串
Array, Set, Map 都有 forEach 方法 for in 遍历对象的可枚举属性,包括其原型链上的属性,且不保证顺序
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 } // 注意目标对象自身也会改变。
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 } |
迭代器协议
可迭代协议
生成器
一点延伸 for of 与 forEach 与 for in
The text was updated successfully, but these errors were encountered: