We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
ES6 规定,默认的Iterator接口部署在数据结构的Symbol.iterator属性。也就是说,一个数据结构只要具有Symbol.iterator属性(Symbol.iterator方法对应的是遍历器生成函数,返回的是一个遍历器对象),那么就可以其认为是可迭代的。
Iterator
Symbol.iterator
(Symbol.iterator
可迭代对象的特点
Symbol.iterator()
for ... of
Array.from
let arry = [1, 2, 3, 4]; let iter = arry[Symbol.iterator](); console.log(iter.next()); // { value: 1, done: false } console.log(iter.next()); // { value: 2, done: false } console.log(iter.next()); // { value: 3, done: false } console.log(iter.next()); // { value: 4, done: false } console.log(iter.next()); // {value: undefined, done: true}
function buildIterator (obj) { return { ...obj, [Symbol.iterator] () { const self = this; const keys = Object.keys(self); let index = 0; return { next () { if (index < keys.length) { return { value: self[keys[index++]], done: false } } else { return { value: undefined, done: true } } } } } }; }
测试
let obj = { name: 'hah', age: 14 } let iter = buildIterator(obj); let list = iter[Symbol.iterator](); console.log(list.next()); // { value: 'hah', done: false } console.log(list.next()); // { value: 14, done: false } console.log(list.next()); // { value: undefined, done: true } for (let item of obj) { console.log(item); // TypeError: obj is not iterable } for (let item of iter) { console.log(item); } // hah // 14
原生具有Iterator接口的数据结构:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
ES6 规定,默认的
Iterator
接口部署在数据结构的Symbol.iterator
属性。也就是说,一个数据结构只要具有Symbol.iterator
属性(Symbol.iterator
方法对应的是遍历器生成函数,返回的是一个遍历器对象),那么就可以其认为是可迭代的。可迭代对象的特点
Symbol.iterator
属性,Symbol.iterator()
返回的是一个遍历器对象for ... of
进行循环Array.from
转换为数组为对象添加Iterator 接口
原生具有
Iterator
接口的数据结构:The text was updated successfully, but these errors were encountered: