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

学习在 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);

}

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


交互式爱情
浏览 84回答 1
1回答

胡说叔叔

current不是变量,它是属性,因此您需要将其引用为this.current.但是,您还有另一个问题this:在this.length和中this[a],this对象不是arrayLikeObject,而是具有方法的对象next()。你也可以解决这个问题,但我认为走另一条路更简单,做next一个箭头函数。这样this.length,this[a]将按预期工作。current在闭包中创建一个普通变量:var arrayLikeObject = {&nbsp; &nbsp; 0: "hello",&nbsp; &nbsp; 1: "there",&nbsp; &nbsp; 2: "crappy coder",&nbsp; &nbsp; length: 3,}arrayLikeObject[Symbol.iterator] = function(){&nbsp; &nbsp; let current = 0;&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; next: () => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(current < this.length) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return {done: false, value: this[current++]};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return {done: true};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };};console.log("after making it iterable: ==============");for(let str of arrayLikeObject) {&nbsp; &nbsp; console.log(str);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript