我需要检查数组中是否至少有一个元素符合条件。 条件取决于变量。
例如,我正在使用这样的东西:
function condition(previousValue, index, array) {
return additonalValue.indexOf(previousValue) + previousValue.indexOf(additonalValue) < -1;
}
我不知道如何将“additonalValue”参数传递给 array.some(condition)
表达式。
我正在使用 jQuery,所以欢迎使用它的替代方案。
有没有办法将参数传递给 array.some() 方法?
最佳答案
如果你想将一个额外的参数传递给放置在 some
方法中的函数,你可以使用 bind
。
var myArray = ['a', 'b', 'c', 'd'];
var otherValue = 'e';
function someFunction(externalParameter, element, index, array) {
console.log(externalParameter, element, index, array);
return (element == externalParameter);
}
myArray.some(someFunction.bind(null, otherValue));
这会给你:
e a 0 ["a", "b", "c", "d"]
e b 1 ["a", "b", "c", "d"]
e c 2 ["a", "b", "c", "d"]
e d 3 ["a", "b", "c", "d"]
false
关于Javascript some() 方法和附加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20999052/