简体   繁体   English

将当前元素+其他参数传递给.every回调函数

[英]Pass current element + other argument to .every callback function

I have a function that checks if an element contains at least N characters. 我有一个检查元素是否至少包含N个字符的函数。 This function takes 2 arguments: the element and the minimum number of characters. 此函数有2个参数:元素和最少字符数。

validateDescription = (input, car) => {
  descriptionInputLength = input.value.replace(/\s/g, "").length;
  valid = descriptionInputLength >= car;
  return valid;
};

I want to execute this function on all the elements of an array using .every but I don't know how to pass the arguments correctly given that it function is called as a callback. 我想使用.every在数组的所有元素上执行此函数,但由于函数被称为回调,因此我不知道如何正确传递参数。

I tried the following, which obviously is not correct (element not defined), but I'm struggling to figure out how to make it work. 我尝试了以下方法,这显然是不正确的(未定义元素),但是我正在努力弄清楚如何使其工作。

exampleArray.every(validateDescription(element, 10))

Every needs function, or reference to function as an argument. Every需要功能,或引用功能作为参数。 But you are passing boolean ( validateDescription() returns boolean) 但是,您正在传递布尔值( validateDescription()返回布尔值)

So, what you need is: 因此,您需要的是:

exampleArray.every(element => validateDescription(element, 10))

or 要么

exampleArray.every(function(element) { return validateDescription(element, 10)})

or 要么

function check(element) {
       return validateDescription(element, 10)
}

exampleArray.every(check)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM