我有一个包含一些值的数组。如何使用 jquery 搜索该数组以获取匹配或接近它的值?
var a = ["foo","fool","cool","god"];
如果我想搜索 oo
,那么它应该返回 foo
、fool
和 cool
因为这些字符串包含 oo
.
最佳答案
普通 JS
要使用 Vanilla JS 在数组中搜索,我将使用 filter()
方法实现到数组原型(prototype)中。
注意:对于非常大型数组,您可能需要考虑将它们重构为async/await函数,否则可能会减慢用户界面的速度.
1。使用正则表达式(较慢)
这是最灵活的方法,因为您可以搜索不同的模式。您应该注意,这里的搜索词不是纯文本,因此您必须根据语法转义大多数非字母数字字符。您不应将未处理的用户输入直接传递给该函数,因为它不会按预期工作。
let a = ["foo","fool","cool","god"];
var term = 'oo'; // search term (regex pattern)
var search = new RegExp(term , 'i'); // prepare a regex object
let b = a.filter(item => search.test(item));
console.log(b); // ["foo","fool","cool"]
2。使用 indexOf
(更快)
在这种特殊情况下,我宁愿使用 indexOf()
这基本上相当于 LIKE %term%
,但在处理大型数组时比使用正则表达式快得多。
执行不区分大小写的搜索是一种常见情况,因此请确保对搜索词和数组项都使用 toLowerCase()
。否则,将其从示例中的所有位置删除。
let a = ["foo","fool","cool","god"];
let term = 'oo';
let b = a.filter(item => item.toLowerCase().indexOf(term) > -1);
console.log(b); // ["foo","fool","cool"]
ES6 风格(ES2015)
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
const filterItems = (needle, heystack) => {
let query = needle.toLowerCase();
return heystack.filter(item => item.toLowerCase().indexOf(query) >= 0);
}
console.log(filterItems('ap', fruits)); // ['apple', 'grapes']
console.log(filterItems('ang', fruits)); // ['mango', 'orange']
ES5 风格
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
function filterItems(needle, heystack) {
var query = needle.toLowerCase();
return heystack.filter(function(item) {
return item.toLowerCase().indexOf(query) >= 0;
})
}
console.log(filterItems('ap', fruits)); // ['apple', 'grapes']
console.log(filterItems('ang', fruits)); // ['mango', 'orange']
This is the outdated answer
To search in the array with jQuery you might use
jQuery.grep()
orjQuery.map()
. Both return new array with filtered elements using a callback function.The fastest implementation (case insensitive) is using
indexOf
andtoUpperCase
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; });
If you don't need case insensitive search you can remove both
.toUpperCase()
to speed it up even further.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); });
or
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; });
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
关于jquery - 如何在 Jquery 中搜索数组,如 SQL LIKE %value% 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5324798/