1. 程式人生 > 其它 >16.迭代器自定義遍歷資料

16.迭代器自定義遍歷資料

<!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> const className = { name: "三年一班", students: ["小明", "小花", "小亮", "小王", "小李"], [Symbol.iterator]() { // 建立索引值 let index = 0; // 儲存this let that = this; return { next: function () { //這裡也可以直接寫今天函式,沒有this指向問題 if (index < that.students.length) { const result = { value: that.students[index], done: false }; // 索引值自增 index++; return result; } else { return { value: undefined, done: true }; } }, }; }, };
// for (const iterator of className.studets) { // console.log(iterator); // }
for (const v of className) { console.log(v); } </script> </body> </html>