index.html 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script>
  11. /**
  12. * 只有实现了 Iterator接口的对象才能够使用 for of 来进行遍历取值
  13. * 每调用一次 next 方法,指针都会向后移动一个位置
  14. */
  15. //声明数组
  16. const arr = [1,2,3,4,5]
  17. //for of 遍历
  18. for(let v of arr){
  19. console.log(v)
  20. }
  21. console.log(arr)
  22. /**
  23. * 迭代器应用
  24. * 自定义遍历数组
  25. */
  26. const bbb = {
  27. name:'aaa',
  28. stus:[
  29. 'zhangsan',
  30. 'lisi',
  31. 'wanger'
  32. ],
  33. [Symbol.iterator](){
  34. let index = 0;
  35. let _this = this
  36. return {
  37. next:function(){
  38. if(index < _this.stus.length){
  39. const res = {
  40. value:_this.stus[index],
  41. done:false
  42. }
  43. index++
  44. return res
  45. }else{
  46. const res = {
  47. value:undefined,
  48. done:true
  49. }
  50. return res
  51. }
  52. }
  53. }
  54. }
  55. }
  56. //使用for of 遍历bbb
  57. for(let v of bbb){
  58. console.log(v)
  59. }
  60. </script>
  61. </body>
  62. </html>