at
Return an element from an array.
Usage
var at = require( '@stdlib/array/base/at' );
at( x, index )
Returns an element from an array.
var x = [ 1, 2, 3, 4 ];
var out = at( x, 0 );
// returns 1
out = at( x, 1 );
// returns 2
out = at( x, -2 );
// returns 3
The function accepts the following arguments:
- x: an input array.
- index: element index.
Notes
If provided an array-like object having an
at
method , the function defers execution to that method and assumes that the method has the following signature:x.at( index )
If provided an array-like object without an
at
method, the function normalizes a provided index and returns a specified element.Negative indices are resolved relative to the last array element, with the last element corresponding to
-1
.If provided out-of-bounds indices, the function always returns
undefined
.
Examples
var discreteUniform = require( '@stdlib/random/array/discrete-uniform' );
var at = require( '@stdlib/array/base/at' );
// Define an array:
var x = discreteUniform( 10, -100, 100 );
// Define an array containing random index values:
var indices = discreteUniform( 100, -x.length, x.length-1 );
// Randomly selected values from the input array:
var i;
for ( i = 0; i < indices.length; i++ ) {
console.log( 'x[%d] = %d', indices[ i ], at( x, indices[ i ] ) );
}