ES6迭代器自定义遍历数据

 //声明一个对象
        const banji = {
                name: "一班",
                stus: [
                    "xiaobai",
                    "xiaohei",
                    "xiaohua",
                    "king"
                ],
                [Symbol.iterator]() {
                    //声明索引变量
                    let index = 0;
                    let _this = this;
                    return {
                        next: function() {
                            if (index < _this.stus.length) {
                                const result = {
                                    value: _this.stus[index],
                                    done: false
                                };
                                index++;
                                return result;
                            } else {
                                return {
                                    value: undefined,
                                    done: true
                                }
                            }

                        }
                    }
                }
            }
            //遍历这个对象
        for (const v of banji) {
            console.log(v);
        }

 

posted @ 2022-10-21 15:39  小白字太白  阅读(26)  评论(0)    收藏  举报