我有一个数组:
[ 4ff023908ed2842c1265d9e4, 4ff0d75c8ed2842c1266099b ]
我必须找出以下是否在该数组中
4ff0d75c8ed2842c1266099b
这是我写的:
Array.prototype.contains = function(k) {
for(p in this)
if(this[p] === k)
return true;
return false;
}
显然,它不能正常工作,或者有时它工作得更好,但在我看来它会阻塞。有没有人可以检查一下?
非常感谢
最佳答案
非阻塞搜索功能
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");
}
});
然而,为了在数组中搜索值,最好使用 Javascript 内置的数组搜索功能,因为它会更快(因此您可能不需要它是非阻塞的):
if ([1, 2, 3, 4, 5].indexOf(3) >= 0) {
console.log("Found");
} else {
console.log("Not found");
}
另外,考虑一下 underscore
库,它使所有东西都跨平台:http://underscorejs.org/
关于node.js - 如何以非阻塞方式在 Node.js 中的数组中搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11286979/