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

后端 未结 8 1047
抹茶落季
抹茶落季 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 16:52

    The second parameter of filter will set this inside of the callback.

    arr.filter(callback[, thisArg])
    

    So you could do something like:

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

提交回复
热议问题