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

时间:2021-09-23 21:46:11

I have an array which is:

我有一个数组是:

[ 4ff023908ed2842c1265d9e4, 4ff0d75c8ed2842c1266099b ]

And I have to find if the following, is inside that array

而且我必须找到以下是否在该数组中

4ff0d75c8ed2842c1266099b

Here is what I wrote:

这是我写的:

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

Apparently, it doesn't work properly, or better sometimes it works, but it looks to me blocking. Is there anyone that can check that one?

显然,它不能正常工作,或者有时它工作得更好,但它看起来阻止我。有人可以检查那个吗?

many thanks

非常感谢

1 个解决方案

#1


32  

Non-blocking search function

非阻塞搜索功能

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));
}

Usage:

用法:

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

However, for searching the value in the array it is better to use Javascript built-in array search function, as it will be much faster (so that you probably won't need it to be non-blocking):

但是,为了搜索数组中的值,最好使用Javascript内置数组搜索功能,因为它会更快(因此你可能不需要它是非阻塞的):

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

Also, consider the underscore library which makes all the stuff cross-platform: http://underscorejs.org/

另外,考虑下划线库,它使所有东西跨平台:http://underscorejs.org/

#1


32  

Non-blocking search function

非阻塞搜索功能

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));
}

Usage:

用法:

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

However, for searching the value in the array it is better to use Javascript built-in array search function, as it will be much faster (so that you probably won't need it to be non-blocking):

但是,为了搜索数组中的值,最好使用Javascript内置数组搜索功能,因为它会更快(因此你可能不需要它是非阻塞的):

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

Also, consider the underscore library which makes all the stuff cross-platform: http://underscorejs.org/

另外,考虑下划线库,它使所有东西跨平台:http://underscorejs.org/