为了账号安全,请及时绑定邮箱和手机立即绑定

为什么迭代器对象变量未定义?

为什么迭代器对象变量未定义?

交互式爱情 2023-05-25 15:41:33

学习在 Javascript 中使对象可迭代。


对象是:


var arrayLikeObject = {

    0: "hello",

    1: "there",

    2: "crappy coder",

    length: 3,

}

然后我这样做以使其可迭代:


arrayLikeObject[Symbol.iterator] = function(){

    return {

        current: 0, // <---- but... it IS defined.

        next() {

            // let current = 0; // putting it here makes it work

            if(current < this.length) {

                let a = current;

                current++;

                return {done: false, value: this[a]};

            }

            else {

                return {done: true};

            }

        }

    };

};

然后当我运行它时:


console.log("after making it iterable: ==============");

for(let str of arrayLikeObject) {

    console.log(str);

}

我得到“当前未定义”但据我所知,它是。我就是不明白。我认为函数可以看到其作用域之外的变量,但反过来却不行,除非如果这是正确的术语,它们会被“掩盖”。我忘了。


查看完整描述

1 回答

?
胡说叔叔

TA贡献1650条经验 获得超8个赞

current不是变量,它是属性,因此您需要将其引用为this.current.


但是,您还有另一个问题this:


在this.length和中this[a],this对象不是arrayLikeObject,而是具有方法的对象next()。


你也可以解决这个问题,但我认为走另一条路更简单,做next一个箭头函数。这样this.length,this[a]将按预期工作。current在闭包中创建一个普通变量:


var arrayLikeObject = {

    0: "hello",

    1: "there",

    2: "crappy coder",

    length: 3,

}


arrayLikeObject[Symbol.iterator] = function(){

    let current = 0;

    return {

        next: () => {

            if(current < this.length) {

                return {done: false, value: this[current++]};

            }

            else {

                return {done: true};

            }

        }

    };

};


console.log("after making it iterable: ==============");

for(let str of arrayLikeObject) {

    console.log(str);

}


查看完整回答
反对 回复 4天前
  • 1 回答
  • 0 关注
  • 6 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信