How do I pass an extra parameter to the callback function in Javascript .filter() method?

后端 未结 8 1017
抹茶落季
抹茶落季 2020-12-22 16:31

I want to compare each string in an Array with a given string. My current implementation is:

function startsWith(element) {
    return element.indexOf(wordTo         


        
8条回答
  •  时光说笑
    2020-12-22 17:00

    You can use the arrow function inside a filter, like this:

    result = addressBook.filter(element => element.indexOf(wordToCompare) === 0);
    

    Arrow functions on MDN

    An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.

提交回复
热议问题