Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

forEach

Invoke a callback function once for each array element.

Usage

var forEach = require( '@stdlib/array/base/for-each' );

forEach( x, fcn[, thisArg] )

Invokes a callback function once for each array element.

var naryFunction = require( '@stdlib/utils/nary-function' );
var log = require( '@stdlib/console/log' );

var x = [ 1, 2, 3, 4 ];

forEach( x, naryFunction( log, 1 ) );

The function accepts the following arguments:

  • x: input array.
  • fcn: callback to apply.
  • thisArg: callback execution context (optional).

To set the callback function execution context, provide a thisArg.

function accumulate( z ) {
    this.sum += z;
}

var x = [ 1, 2, 3, 4 ];

var ctx = {
    'sum': 0
};

forEach( x, accumulate, ctx );
var sum = ctx.sum;
// returns 10

The callback function is provided the following arguments:

  • value: current array element.
  • index: current array element index.
  • arr: the input array.

Notes

  • If provided an array-like object having a forEach method, the function defers execution to that method and assumes that the method API has the following signature:

    x.forEach( fcn, thisArg )
    
  • The function support array-like objects having getter and setter accessors for array element access (e.g., @stdlib/array/base/accessor).

Examples

var discreteUniform = require( '@stdlib/random/array/discrete-uniform' );
var naryFunction = require( '@stdlib/utils/nary-function' );
var log = require( '@stdlib/console/log' );
var forEach = require( '@stdlib/array/base/for-each' );

var x = discreteUniform( 10, 0, 10, {
    'dtype': 'float64'
});

forEach( x, naryFunction( log, 1 ) );