字符串迭代行为


var someString = new String('hi');
someString[Symbol.iterator] = function() {
return { // this is the iterator object, returning a single element, the string "bye"
next: function() {
if (this._first) {
this._first = false;
return { value: 'bye', done: false };
} else {
return { done: true };
}
},
_first: true
};
};

这段代码是为MDN中的字符串迭代行为机制编写的,但我无法理解变量_first的用法、使用它的原因以及它在哪里声明。

在代码片段中,迭代器对象有两个属性:

  • next-一个函数
  • _first-一个布尔标志,它被初始化为true

next函数检查_first,看看这是否是第一次调用该函数,并相应地调整其行为。

请注意,在next函数内部,this将引用迭代器对象,因此可以用于访问_first属性。

最新更新