考虑以下标准使用Array.prototype.find:
var getObject = myObjects.find(callback);
使用:
var callback = function(object) {
return object === 'myValue'
}
有没有办法注入另一个参数?所以我们有,比如说:
var getObject = myObjects.find(callback, mySearchTerm);
使用:
var callback = function(element, mySearchTerm) {
return element === mySearchTerm;
}
答案 0 :(得分:1)
var term = 'some term';
var getObject = myObjects.find(function(item){return callback(item, term)});
答案 1 :(得分:0)
你可以在参数上使用闭包,比如
var callback = function (value) {
return function(object) {
return object === value;
};
};
使用参数
调用回调var getObject = myObjects.find(callback(mySearchTerm));
答案 2 :(得分:0)
您可以使用包装函数来实现可重用的解决方案。
示例:
var myObjects = [1, 2, 2, 3, 4];
var search = function(data, mySearchTerm) {
var callback = function(element) {
return element === mySearchTerm;
};
return data.find(callback)
};
var getObject = search(myObjects, 2);
console.log(getObject);

或者
var myObjects = [1, 2, 2, 3, 4];
var mySearchTerm = 2;
var callback = function(object) {
return object === mySearchTerm;
};
var getObject = myObjects.find(function(element) {
return callback(element, mySearchTerm);
});
console.log(getObject);

答案 3 :(得分:0)
以下是一个例子:
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function myFind(what){
function findCherries(fruit) {
return fruit.name === what;
}
return inventory.find(findCherries)
}
console.log(myFind("cherries"));
但同样,IE不支持array.find()!