简体   繁体   中英

Calling function in forEach with extra parameters

I am trying to substitute an anonymous function call in javascript, for a real function in a forEach.

What I have is something like:

whatever: function( importantParam ) {
  array.forEach( function ( val ) {
      if ( val === importantParam ) console.log( "OK" );
  } );
}

What I want to achieve is something like:

whatever: function( importantParam ) {
  array.forEach(this.whatever2,this);
},
whatever2: function( p1, importantParam) {
      if ( p1 === importantParam ) console.log( "OK" );
}

So the problem is that I don't really know how to pass the importantParam when i call whatever2 inside forEach, since it takes a function as argument with 2 arguments for they index and the value, and nothing else.

You'll need to wrap whatever2 somehow, eg using .bind

var array = [1, 2, 3],
    obj;
obj = {
    whatever: function (importantParam) {
        array.forEach(this.whatever2.bind(this, importantParam));
    },
    whatever2: function (importantParam, p1) {
        if (p1 === importantParam)
            console.log("OK");
    }
};

obj.whatever(2); // logs OK

In ES6 you can clean this up and use arrow functions

let obj = {
    whatever(importantParam) {
        array.forEach(x => this.whatever2(x, importantParam));
    },
    whatever2(p1, importantParam) {
        if (p1 === importantParam)
            console.log("OK");
    }
};

Please note that this example use case you've provided looks like you should actually use .some instead of .forEach and return true where you do the log

Wrap it with another function

whatever: function( importantParam ) {
  array.forEach(function(item) {
     this.whatever2(item, importantParam);
  },this);
},

or switch the order of arguments and use bind to partially apply callback

whatever: function( importantParam ) {
  array.forEach(this.whatever2.bind(this, importantParam));
},
whatever2: function(importantParam, p1) {
      if ( p1 === importantParam ) console.log( "OK" );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM