我有一个数组是:
[ 4ff023908ed2842c1265d9e4, 4ff0d75c8ed2842c1266099b ]
Run Code Online (Sandbox Code Playgroud)
我必须找到以下内容,是否在该数组中
4ff0d75c8ed2842c1266099b
Run Code Online (Sandbox Code Playgroud)
这是我写的:
Array.prototype.contains = function(k) {
for(p in this)
if(this[p] === k)
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
显然,它不能正常工作,或者更好,但有时它可以工作,但它看起来阻止我.有没有人可以检查那个?
非常感谢
pen*_*tur 32
非阻塞搜索功能
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));
}
Run Code Online (Sandbox Code Playgroud)
用法:
[1, 2, 3, 4, 5].contains(3, function(found) {
if (found) {
console.log("Found");
} else {
console.log("Not found");
}
});
Run Code Online (Sandbox Code Playgroud)
但是,为了搜索数组中的值,最好使用Javascript内置数组搜索功能,因为它会更快(因此您可能不需要它是非阻塞的):
if ([1, 2, 3, 4, 5].indexOf(3) >= 0) {
console.log("Found");
} else {
console.log("Not found");
}
Run Code Online (Sandbox Code Playgroud)
另外,考虑underscore使所有东西跨平台的库:http://underscorejs.org/