我正在使用 jquery grep 搜索对象数组,并希望在搜索中包含通配符。例如,我有一个数组如下:
courses = [
{code: 'ENCH3TH', otherFields: otherStuff},
{code: 'ENCH3THHS1', otherFields: otherStuff},
{code: 'ENCH3TH2', otherFields: otherStuff},
{code: 'ENCH4RT', otherFields: otherStuff},
{code: 'ENCH4MT', otherFields: otherStuff}]
我想获取所有带有 ENCH3TH 前缀的类(class)。我已经尝试过
var resultSet = $.grep(courses, function(e){ return e.code == 'ENCH3TH/'; });
..无济于事(请注意在“ENCH3TH”之后使用“/”作为通配符)。
最佳答案
您可以使用String.indexOf()此处,=
不适用于通配符
var resultSet = $.grep(courses, function (e) {
return e.code.indexOf('ENCH3TH') == 0;
});
演示:Fiddle
或者使用正则表达式
var regex = /^ENCH3TH/
var resultSet = $.grep(courses, function (e) {
return regex.test(e.code);
});
演示:Fiddle
关于jquery - 使用带有通配符的 jquery grep 搜索对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18757848/