問題描述
從 Javascript 1.7 開始,有一個 Iterator 對象,它允許這樣做:
Since Javascript 1.7 there is an Iterator object, which allows this:
var a={a:1,b:2,c:3};
var it=Iterator(a);
function iterate(){
try {
console.log(it.next());
setTimeout(iterate,1000);
}catch (err if err instanceof StopIteration) {
console.log("End of record.
");
} catch (err) {
console.log("Unknown error: " + err.description + "
");
}
}
iterate();
node.js 中有這樣的東西嗎?
is there something like this in node.js ?
我現(xiàn)在正在使用:
function Iterator(o){
/*var k=[];
for(var i in o){
k.push(i);
}*/
var k=Object.keys(o);
return {
next:function(){
return k.shift();
}
};
}
但是通過將所有對象鍵存儲在 k
中會產(chǎn)生大量開銷.
but that produces a lot of overhead by storing all the object keys in k
.
推薦答案
你想要的是對對象或數(shù)組的惰性迭代.這在 ES5 中是不可能的(因此在 node.js 中是不可能的).我們最終會得到這個.
What you want is lazy iteration over an object or array. This is not possible in ES5 (thus not possible in node.js). We will get this eventually.
唯一的解決方案是找到一個擴展 V8 的節(jié)點模塊來實現(xiàn)迭代器(可能還有生成器).我找不到任何實現(xiàn).您可以查看 spidermonkey 源代碼并嘗試使用 C++ 將其編寫為 V8 擴展.
The only solution is finding a node module that extends V8 to implement iterators (and probably generators). I couldn't find any implementation. You can look at the spidermonkey source code and try writing it in C++ as a V8 extension.
您可以嘗試以下方法,但它也會將所有鍵加載到內(nèi)存中
You could try the following, however it will also load all the keys into memory
Object.keys(o).forEach(function(key) {
var val = o[key];
logic();
});
然而,由于 Object.keys
是一種原生方法,它可能會帶來更好的優(yōu)化.
However since Object.keys
is a native method it may allow for better optimisation.
基準測試
如您所見,Object.keys 明顯更快.實際的內(nèi)存存儲是否更優(yōu)化是另一回事.
As you can see Object.keys is significantly faster. Whether the actual memory storage is more optimum is a different matter.
var async = {};
async.forEach = function(o, cb) {
var counter = 0,
keys = Object.keys(o),
len = keys.length;
var next = function() {
if (counter < len) cb(o[keys[counter++]], next);
};
next();
};
async.forEach(obj, function(val, next) {
// do things
setTimeout(next, 100);
});
這篇關(guān)于迭代 node.js 中的對象鍵的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!