How to pass function to compare items?
-
11-12-2019 - |
Domanda
I would like to pass a comparer into a function and not sure if this is possible with Javascript. There is an IComparer concept in C# that does this. Can this be done in Javascript?
function someAction (comparer) {
var newList = [];
$.each(list, function (index, item) {
if comparer on item is true then { //psuedo code
newList.push(item);
}
});
}
someAction(item.PropA > 5);
Soluzione
function someAction (comparer) {
var newList = [];
$.each(list, function (index, item) {
if (comparer(item)) {
newList.push(item);
}
});
}
someAction(function (item) { return item.PropA > 5 });
PS: as @BrokenGlass suggested, you can avoid reinventing the wheel and use the filter
function.
Altri suggerimenti
Just call the function:
if (comparer(item)) { ... }
All references to functions in JavaScript are equivalent, so any reference can be used to invoke a function in the same way any other reference can be used. Functions are first-class objects, in other words.
You might be looking for filter
, which already exists in JavaScript:
var newList = list.filter(function(item) {
return item.PropA > 5;
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow