@stdlib/array-base-for-each
v0.1.1
Published
Invoke a callback function once for each array element.
Readme
forEach
Invoke a callback function once for each array element.
Installation
npm install @stdlib/array-base-for-eachUsage
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 10The 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
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).
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 ) );Notice
This package is part of stdlib, a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.
For more information on the project, filing bug reports and feature requests, and guidance on how to develop stdlib, see the main project repository.
Community
License
See LICENSE.
Copyright
Copyright © 2016-2026. The Stdlib Authors.
