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
Iterator 概念:iterator是一种接口机制,为各种不同的数据结构提供统一的访问机制
{ value: 当前成员的值, done: 布尔值 }
看代码:
/** * 自己实现一个 迭代器 * * @param {*} source * @returns */ function myIterator(source) { let nextIndex = 0 return { next: function() { return nextIndex < source.length ? { value: source[nextIndex++], done: false, } : { value: undefined, done: true, } } } } // test iterator const arr = [1,2,3, {name: 'Tom', age: 18}, 'hello, tom'] const testIteratorObj = myIterator(arr) console.log(testIteratorObj.next()) console.log(testIteratorObj.next()) console.log(testIteratorObj.next()) console.log(testIteratorObj.next()) console.log(testIteratorObj.next()) console.log(testIteratorObj.next()) // 结果: // { value: 1, done: false } // { value: 2, done: false } // { value: 3, done: false } // { value: { name: 'Tom', age: 18 }, done: false } // { value: 'hello, tom', done: false } // { value: undefined, done: true }
以下类型数据原生具备 iterator 接口——可以用 for...of 遍历
注意: 没有 Object,对象没有 iterator 接口
const obj = { name: 'Tom', age: 18 } for (let i of obj) { console.log(obj[i]) } //TypeError: obj is not iterable
这里,说明下 arguments 的用法,看代码:
// 不用定义参数,使用 arguments 获取到 function fun() { for (let i of arguments) { console.log(arguments[i]) } } fun(1, 'b', 3, {name: 'Tom'}, false) // 结果 // 1 // b // 3 // { name: 'Tom' } // false
对于 拓展运算符(... 运算符) 和 解构赋值,本质上还是 iterator 的使用,它们会默认去调用 iterator 接口
...
更多学习资料,参考:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
作用
工作原理
自己实现一个 iterator
看代码:
拓展
以下类型数据原生具备 iterator 接口——可以用 for...of 遍历
注意: 没有 Object,对象没有 iterator 接口
这里,说明下 arguments 的用法,看代码:
拓展
对于 拓展运算符(
...
运算符) 和 解构赋值,本质上还是 iterator 的使用,它们会默认去调用 iterator 接口更多学习资料,参考:
The text was updated successfully, but these errors were encountered: