1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <script>
- /**
- * 只有实现了 Iterator接口的对象才能够使用 for of 来进行遍历取值
- * 每调用一次 next 方法,指针都会向后移动一个位置
- */
- //声明数组
- const arr = [1,2,3,4,5]
- //for of 遍历
- for(let v of arr){
- console.log(v)
- }
- console.log(arr)
- /**
- * 迭代器应用
- * 自定义遍历数组
- */
- const bbb = {
- name:'aaa',
- stus:[
- 'zhangsan',
- 'lisi',
- 'wanger'
- ],
- [Symbol.iterator](){
- let index = 0;
- let _this = this
- return {
- next:function(){
- if(index < _this.stus.length){
- const res = {
- value:_this.stus[index],
- done:false
- }
- index++
- return res
- }else{
- const res = {
- value:undefined,
- done:true
- }
- return res
- }
- }
- }
- }
- }
- //使用for of 遍历bbb
- for(let v of bbb){
- console.log(v)
- }
-
- </script>
- </body>
- </html>
|