如何寻找一个数组jQuery中,如SQL LIKE%值%的语句 [英] How to search an array in Jquery like SQL LIKE %value% statement

查看:418
本文介绍了如何寻找一个数组jQuery中,如SQL LIKE%值%的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些值的数组。我如何使用jquery为其匹配或值搜索该阵列接近它?

I have an array with some values. How can I search that array using jquery for a value which is matched or close to it?

var a = ["foo","fool","cool","god"];

如果我想搜索 OO ,那么它应该返回傻瓜,因为这些字符串包含 OO

If I want to search for oo, then it should return foo, fool, and cool because these strings contain oo.

推荐答案

要在数组中搜索你必须使用 jQuery.grep() jQuery.map()。都返回使用一个回调函数过滤元素新的数组。

To search in the array you have to use jQuery.grep() or jQuery.map(). Both return new array with filtered elements using a callback function.

最快的实现(不区分大小写)中使用的indexOf 与toUpperCase 在回调:

The fastest implementation (case insensitive) is using indexOf and toUpperCase in the callback:

var search_term = 'oo'; // your search term as string
var search = search_term.toUpperCase();
var array = jQuery.grep(a, function(value) {
    return value.toUpperCase().indexOf(search) >= 0;
});

如果您不需要区分大小写的搜索都可以删除 .toUpperCase()来进一步加快速度。

If you don't need case insensitive search you can remove both .toUpperCase() to speed it up even further.

更灵活,但是慢得多(配不上小数组)是使用常规的前pression:

More flexible but much slower (good enough for small arrays) is to use regular expression:

var search_term = "oo"; // search term
var search = new RegExp(search_term , "i");
var arr = jQuery.grep(a, function (value) {
    return search.test(value);
});

var search_term = "oo"; // search term
var search = new RegExp(search_term , "i");
var arr = jQuery.map(a, function (value) {
    return value.match(search) ? value : null;
});

正前pressions让你做出的搜索比%值%要复杂得多。但是,如果你不需要它,因为它是慢很多时候不使用它。

Regular expressions allow you to make searches much more complex than %value%. However don't use it if you don't need it because it is many times slower.

你应该得到一个数组改编通过匹配的元素

you should get an array arr with the matched elements

更新:变更为例子,以避免硬codeD搜索词(根据意见的问题),并简化了code

UPDATE: Changed the examples to avoid the hardcoded search term (according to the question in comments) and simplified the code

UPDATE2:从正则表达式删除了G标记

UPDATE2: Removed the "g" flag from the regex

这篇关于如何寻找一个数组jQuery中,如SQL LIKE%值%的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆