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

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

    There is an easy way to use the filter function, access all params, and not over complicate it.

    Unless the callback's thisArg is set to another scope filter does not create its own scope, and we can access params within the current scope. We can set 'this' to define a different scope in order to access other values if needed, but by default it is set to the scope it's called from. You can see this being used for Angular scopes in this stack.

    Using indexOf is defeating the purpose of filter, and adding more overhead. Filter is already going through the array, so why do we need to iterate through it again? We can instead make it a simple pure function.

    Here's a use-case scenario within a React class method where the state has an array called items, and by using filter we can check the existing state:

    checkList = (item) => {  // we can access this param and globals within filter
      var result = this.state.filter(value => value === item); // returns array of matching items
    
      result.length ? return `${item} exists` : this.setState({
        items: items.push(item) // bad practice, but to keep it light
      });
    }
    

提交回复
热议问题