3

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
4

4 に答える 4

2

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

よりエレガントにするために、この回答で提供されているように、ブールアグリゲーター関数を使用できます。

val2_in_array = $.some(values, function() {
    return this.id == val2_anotherInstance.id
});
于 2012-04-19T08:05:21.837 に答える
1

この関数をタスクに使用できます。

$.fn.inArrayCallback = function(needle, haystack, f) {
  var e = -1;
  $.each(haystack,function(index, value){
      if (f(needle,value)) { e = index; return false; }
    });
  return e;
}

ans = $.fn.inArrayCallback(val2_anotherInstance, values, valueComparer) > -1; 
// returns true

grep関数で回答すると、一致する要素が既に見つかっている場合でも、配列内のすべての要素が検索されます。この関数は一致すると検索を停止します。これは、非常に大きな配列では重要な場合があります。

于 2012-04-19T08:42:14.570 に答える
0

greep()関数を使用して配列をフィルタリングし、生成された配列内の項目を数えることができます。ただし、すべての配列を処理するため、大量のデータがある場合はパフォーマンスが低下します。

于 2012-04-19T08:05:30.507 に答える
0

jquery map 関数が問題を解決するはずです。マップのコールバックで比較ロジックを実装できます。 jQueryマップを参照

于 2012-04-19T08:16:53.590 に答える