javascript-jQuery指定用于在数组中搜索值的条件

JavaScript中,我需要知道数组是否包含值.值是对象,我可以拥有同一对象的不同实例,这意味着$.inArray(…)将无法工作.我知道如何使用$.each(…)来完成我的任务,我的问题是-是否可以将具有值比较逻辑的函数传递给任何jQuery方法(请参见具有所需sintax的示例)?

    // values
var val1 = { id: 1, description: 'First value'};
var val2 = { id: 2, description: 'Second value'};
var val3 = { id: 3, description: 'Third value'};        
// array of values
var values = [ val1, val2, val3 ];
// inArray of jQuery to know if value is in array -> returns TRUE
var isInArray = $.inArray(val2, values) > -1;

// another instance of same object "val2"
var val2_anotherInstance = { id: 2, description: 'Second value'};
// inArray works as expected -> returns FALSE but desirable result is TRUE
var isInArray_anotherInstance = $.inArray(val2_anotherInstance, values) > -1;

// define function for comparing values (any logic can be implemented, for example searching by Id)
var valueComparer = function(first, second) {
    return first.id == second.id && first.description == second.description;
}
// function compares objects and returns true for different instances
alert(valueComparer(val2, val2_anotherInstance));

// desirable sintax:
// is something like this possible ???      
// NOTE next line not correct
isInArray_anotherInstance = $.inArray(val2_anotherInstance, values, valueComparer) > -1;
// actually what I want is specify criteria for searching value in array

解决方法:

尝试grep

var val1 = { id: 1, description: 'First value'};
var val2 = { id: 2, description: 'Second value'};
var val3 = { id: 3, description: 'Third value'};        

var values = [ val1, val2, val3 ];

// another instance of same object "val2"
var val2_anotherInstance = { id: 2, description: 'Second value'};


var items = $.grep(values, function(x) {
    return x.id == val2_anotherInstance.id
})

var found = items.length > 0

为了更加美观,可以使用this answer中提供的布尔聚合函数:

val2_in_array = $.some(values, function() {
    return this.id == val2_anotherInstance.id
});
上一篇:xpath和contains模糊匹配


下一篇:LeetCode 220. Contains Duplicate III (分桶法)