자바 스크립트에서 배열에 값이 들어 있는지 알아야합니다. 값은 객체이며 동일한 객체의 다른 인스턴스를 가질 수 있습니다. 즉, $ .inArray (...)가 작동하지 않습니다. $ .each (...)를 사용하여 작업을 수행하는 방법을 알고 있고 내 질문은 - 값을 비교 논리로 함수를 jQuery 메서드에 전달할 수 있습니까 (원하는 sintax가있는 샘플 참조)?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
불행히도'inArray()'는 함수를 사용하지 않습니다. 'grep()' – elclanrs