gpt4 book ai didi

javascript - 为 JavaScript 对象编写枚举器

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:00 26 4
gpt4 key购买 nike

我正在尝试了解如何编写 JavaScript 对象的枚举器。我偶然发现了一段 Sharepoint code where items of a SP List were being obtained on the client side ,并且在 Sharepoint 对象上执行了类似于下面的代码。

var enumerator = list.getEnumerator();
while(enumerator.moveNext()) {
var currentItem = enumerator.getCurrent();
// actions on currentItem
}

如果我可以编写一个自定义对象,可以像上面那样使用枚举器进行迭代,它会是什么样子?这是我的尝试,但它不起作用:

var list = {
items: ["A", "B", "C", "D", "E"],
counter: -1,
enumerator: {
moveNext: function() {
counter++; // outer object's variable not accessible
if(counter >= items.length)
return false;
else
return true;
},
getCurrent: function() {
return items[counter]; // outer object's variable not accessible
}
},
getEnumerator: function() {
return this.enumerator();
}
}

var enumerator = list.getEnumerator();
while(enumerator.moveNext()) {
var currentItem = enumerator.getCurrent();
alert(currentItem);
}

你能帮我理解如何将 getEnumerator() 写成适用于任何可枚举对象的函数原型(prototype)吗?

最佳答案

尝试以下:

var list = function() {
// these local variables could be accessed by inner functions.
var items = ["A", "B", "C", "D", "E"],
counter = -1;
return {
enumerator: {
moveNext: function() {
counter++;
return counter < items.length;
},
getCurrent: function() {
return items[counter];
}
},
getEnumerator: function() {
// here should not be return this.enumerator() but just this.enumerator
return this.enumerator;
}
};
};

var enumerator = list().getEnumerator();
while(enumerator.moveNext()) {
var currentItem = enumerator.getCurrent();
alert(currentItem);
}

THE JSFIDDLE DEMO.

关于javascript - 为 JavaScript 对象编写枚举器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22611836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com