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

后端 未结 8 1019
抹茶落季
抹茶落季 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.

    0 讨论(0)
  • 2020-12-22 17:02

    Make startsWith accept the word to compare against and return a function which will then be used as filter/callback function:

    function startsWith(wordToCompare) {
        return function(element) {
            return element.indexOf(wordToCompare) === 0;
        }
    }
    
    addressBook.filter(startsWith(wordToCompare));
    

    Another option would be to use Function.prototype.bind [MDN] (only available in browser supporting ECMAScript 5, follow a link for a shim for older browsers) and "fix" the first argument:

    function startsWith(wordToCompare, element) {
        return element.indexOf(wordToCompare) === 0;
    }
    
    addressBook.filter(startsWith.bind(this, wordToCompare));
    

    I dont really understand how the default parameters it takes are passed

    There is nothing special about it. At some point, filter just calls the callback and passes the current element of the array. So it's a function calling another function, in this case the callback you pass as argument.

    Here is an example of a similar function:

    function filter(array, callback) {
        var result = [];
        for(var i = 0, l = array.length; i < l; i++) {
            if(callback(array[i])) {  // here callback is called with the current element
                result.push(array[i]);
            }
        }
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题