如何以非阻塞的方式在Node.js中search数组?

我有一个数组是:

[ 4ff023908ed2842c1265d9e4, 4ff0d75c8ed2842c1266099b ] 

而且我必须find,如果下面,在这个数组里面

 4ff0d75c8ed2842c1266099b 

这是我写的:

 Array.prototype.contains = function(k) { for(p in this) if(this[p] === k) return true; return false; } 

显然,它不能正常工作,或者有时候它可以工作,但是在我看来阻塞。 有没有人可以检查那个?

非常感谢

非阻塞searchfunction

 Array.prototype.contains = function(k, callback) { var self = this; return (function check(i) { if (i >= self.length) { return callback(false); } if (self[i] === k) { return callback(true); } return process.nextTick(check.bind(null, i+1)); }(0)); } 

用法:

 [1, 2, 3, 4, 5].contains(3, function(found) { if (found) { console.log("Found"); } else { console.log("Not found"); } }); 

但是,为了在数组中search值,最好使用Javascript内置的数组searchfunction,因为它会快得多(所以你可能不需要它是非阻塞的):

 if ([1, 2, 3, 4, 5].indexOf(3) >= 0) { console.log("Found"); } else { console.log("Not found"); } 

另外,请考虑使所有的东西跨平台的underscore库: http : //underscorejs.org/