我试图理解如何编写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()
写成适用于任何可枚举对象的函数原型吗?
答案 0 :(得分:3)
尝试以下:
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. 强>
答案 1 :(得分:1)
您可以使用list.
var list = {
items: ["A", "B", "C", "D", "E"],
counter: -1,
enumerator: {
moveNext: function() {
list.counter++; // outer object's variable not accessible
if(list.counter >= list.items.length)
return false;
else
return true;
},
getCurrent: function() {
return list.items[list.counter]; // outer object's variable not accessible
}
},
getEnumerator: function() {
return list.enumerator;
}
}
或者您可以创建一个函数来创建它的实例
function makeList(items) {
var list = {
items: items
counter: -1,
enumerator: {
moveNext: function() {
list.counter++; // outer object's variable not accessible
if(list.counter >= list.items.length)
return false;
else
return true;
},
getCurrent: function() {
return list.items[list.counter];
}
},
getEnumerator: function() {
return list.enumerator;
}
return list;
}
var enumerator = makeList(["A", "B", "C", "D", "E"]).getEnumerator();
答案 2 :(得分:1)
感谢来自@xdazz和@Juan Mendes的指针,我能够计算出枚举器函数原型:
Array.prototype扩展名:
Array.prototype.getEnumerator = Array.prototype.getEnumerator ||
function() {
var items = this;
var counter = -1;
var enumerator = {
moveNext: function() {
counter++;
return (counter < items.length);
},
getCurrent: function() {
return items[counter];
}
}
return enumerator;
};
<强>用法:强>
var list = ["A", "B", "C", "D", "E"];
var enumerator = list.getEnumerator(); // makes any array enumerable
while(enumerator.moveNext()) {
var currentItem = enumerator.getCurrent();
alert(currentItem);
}
<强> JSFIDDLE DEMO 强>