Invoke a callback function once for each array element.
var forEach = require( '@stdlib/array/base/for-each' );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 10The callback function is provided the following arguments:
- value: current array element.
- index: current array element index.
- arr: the input array.
-
If provided an array-like object having a
forEachmethod, 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).
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 ) );