Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

javascript - 迭代node.js中的对象键(Iterate over object keys in node.js)

Since Javascript 1.7 there is an Iterator object, which allows this:(从Javascript 1.7开始,有一个Iterator对象,允许这样:)

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(); is there something like this in node.js ?(在node.js中有这样的东西吗?) Right now i'm using:(现在我正在使用:) function Iterator(o){ /*var k=[]; for(var i in o){ k.push(i); }*/ var k=Object.keys(o); return { next:function(){ return k.shift(); } }; } but that produces a lot of overhead by storing all the object keys in k .(但是通过将所有对象键存储在k中会产生大量开销。)   ask by stewe translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you want is lazy iteration over an object or array.(你想要的是对对象或数组的懒惰迭代。)

This is not possible in ES5 (thus not possible in node.js).(这在ES5中是不可能的(因此在node.js中是不可能的)。) We will get this eventually.(我们最终会得到这个。) The only solution is finding a node module that extends V8 to implement iterators (and probably generators).(唯一的解决方案是找到一个扩展V8的节点模块来实现迭代器(可能还有生成器)。) I couldn't find any implementation.(我找不到任何实现。) You can look at the spidermonkey source code and try writing it in C++ as a V8 extension.(您可以查看spidermonkey源代码,并尝试将其作为V8扩展在C ++中编写。) 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(); }); However since Object.keys is a native method it may allow for better optimisation.(但是,由于Object.keys是一种本机方法,因此可以实现更好的优化。) Benchmark(基准) As you can see Object.keys is significantly faster.(正如您所看到的,Object.keys明显更快。) 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); });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...