将数组转换为游标
使用.toArray(foo)
方法可以轻松地将游标转换为数组:
var cursor = col.find({}); cursor.toArray(function (err, itemsArray) { /* do something */ });
但是是否有可能转换itemsArray
中的itemsArray
,所以我会有所有的游标函数?
var newCursor = foo (itemsArray); typeof newCursor.toArray === "function" // true
那么这只是JavaScript所以为什么不创build自己的迭代器:
var Iterator = function () { var items = []; var index = 0; return { "createCursor" : function (listing) { items = listing; }, "next" : function () { if ( this.hasNext() ) { return items[index++]; } else { return null; } }, "hasNext" : function () { if ( index < items.length ) { return true; } else { return false; } } } }();
那么你就像这样用一个数组来使用它:
var cursor = new Iterator(); cursor.createCursor( array ); cursor.next(); // returns just the first element of the array
所以只是写一个迭代器的一般方法。 如果你想要更多的function,那么只需将其他方法添加到原型。