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

标签 javascript jquery arrays contains

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

    // 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

为了更优雅,您可以使用 bool 聚合器函数,如 this answer 中提供的那样:

val2_in_array = $.some(values, function() {
    return this.id == val2_anotherInstance.id
});

关于javascript - jQuery 指定在数组中搜索值的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10223902/

相关文章:

javascript - jQuery click 与 AngularJS ng-click 结合使用不触发

javascript - 使用 jquery 更新时间跨度

javascript - 将文本框悬停在菜单/子菜单项中会关闭最新 Chrome 版本中的项目

javascript - 在javascript函数中通过EL访问模型对象?

jquery - 在 Mac 浏览器(如 safari/chrome)上的绝对/相对元素上显示 block /无

c - 字符串段错误问题

java - 打印数组的索引和元素

javascript - 如何在特定索引处将项目插入到数组中 (JavaScript)

javascript - 增加/减少 url 路径名单击

javascript - 从浏览器打开我的 Electron 应用程序时如何获取输入