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

后端 未结 8 1059
抹茶落季
抹茶落季 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:55

    For anyone wondering why their fat arrow function is ignoring [, thisArg], e.g. why

    ["DOG", "CAT", "DOG"].filter(animal => animal === this, "DOG") returns []

    it's because this inside those arrow functions are bound when the function is created and are set to the value of this in the broader encompassing scope, so the thisArg argument is ignored. I got around this pretty easily by declaring a new variable in a parent scope:

    let bestPet = "DOG"; ["DOG", "CAT", "DOG"].filter(animal => animal === bestPet); => ["DOG", "DOG"]

    Here is a link to some more reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this

提交回复
热议问题