File tree Expand file tree Collapse file tree 1 file changed +28
-18
lines changed Expand file tree Collapse file tree 1 file changed +28
-18
lines changed Original file line number Diff line number Diff line change @@ -418,6 +418,20 @@ console.log(toString=== Number.prototype.toString); // true
418418 }
419419 ` ` `
420420
421+ ` ` ` js
422+ // for...of的本质
423+ function forOf(iteratorInstance, fn) {
424+ let it = iteratorInstance[Symbol.iterator]()
425+ let result = it.next()
426+ while (!result.done) {
427+ // 执行for...of中的代码
428+ fn(result.value)
429+ // 给result重新赋值
430+ result = it.next()
431+ }
432+ }
433+ ` ` `
434+
421435- Array .prototype .forEach 方法无法使用break 中断,可通过try / catch + throw 解决
422436 ` ` ` javascript
423437 try {
@@ -542,24 +556,6 @@ const syncIteratorObj = transformSyncIterator(obj)
542556for(const value of syncIteratorObj) {
543557 console.log(value)
544558}
545- // for...of本质:
546- // const it = syncIteratorObj[Symbol.iterator]()
547- // let result = it.next()
548- // while(!result.done) {
549- // console.log(result.value)
550- // result = it.next()
551- // }
552-
553- // 应用:普通对象转化为迭代器对象,使能使用数组解构方式
554- const person = {
555- name: 'Bob',
556- age: 12,
557- // 使用生成器函数实现迭代器更简单,具体见生成器函数部分
558- *[Symbol.iterator]() {
559- yield* Object.values(this)
560- }
561- }
562- console.log([...person]) // [ 'Bob', 12 ]
563559` ` `
564560
565561- 普通对象转化为异步迭代器对象
@@ -594,3 +590,17 @@ const asyncIteratorObj = transformAsyncIterator(obj2)
594590 }
595591})()
596592` ` `
593+
594+ - 应用
595+ ` ` ` js
596+ // 普通对象转化为迭代器对象,使能使用数组解构方式
597+ const person = {
598+ name: 'Bob',
599+ age: 12,
600+ // 使用生成器函数实现迭代器更简单,具体见生成器函数部分
601+ *[Symbol.iterator]() {
602+ yield* Object.values(this)
603+ }
604+ }
605+ console.log([...person]) // [ 'Bob', 12 ]
606+ ` ` `
You can’t perform that action at this time.
0 commit comments