在JavaScript中压缩数组

什么是JavaScript相当于Ruby的Array#compact?

长版本….我跟着在blog.nemikor.com的例子。 他的最后一个例子closures了旧的要求,但是随后的pendings仍然被pendings 。 这看起来像是一个内存泄漏给我。

我的解决scheme是迭代filter如下所示,但这似乎有可能是pendings.pushpendings = pendings.filter之间的竞争条件。 我是偏执狂吗? 如果存在竞争条件,我该如何解决?

 var pendings = []; // there is a route app.get('/some/path', function (request, response) { pendings.push({ response: response, requestedAt: new Date().getTime() }); }); setInterval(function () { var expiration = new Date().getTime() - (1000 * 30); pendings = pendings.filter(function (pending, index) { if (pending.requestedAt > expiration) { return true; } else { pending.response.writeHead(408, { 'Content-Type': 'text/plain' }); pending.response.end(''); } }); }, 1000); 

你在JavaScript中没有线程,所以没有竞争条件。 所有代码都是按顺序排列的,只有在运行完成后才能传输控件。 所以你的间隔函数将运行到完成之前,任何其他function将触摸pendings

这适用于setTimeoutsetInterval类的东西。

作为一个实验:如果你使用setTimeout超时1秒后超时。 在此之后,你写一个while循环阻塞2秒,超时将之后触发,远远超过1秒。

粗俗的东西:

 var timer = setTimeout(function () { alert("hi!"); }, 1000); var now = new Date(); var till = new Date(now + 2); while(new Date() < till) {} // block for 2 seconds 

你可能想看看Underscore.js库
http://documentcloud.github.com/underscore/

这提供了许多有用的低级函数来处理集合,数组和对象。 它包括一个compactfunction(虽然我认为它为您正在寻找什么不同的目的)和一个filterfunction。

只要你没有做I / O操作,也就是说你只是在执行内存操作,那么保证不会中断(由于事件循环的性质)。

因此,如果收集时间过长(比如数千或更多),请小心,因为您可以阻止事件循环一段时间,而不会让其他请求得到服务。