Nodejs Array ForEach _forEach(callback)

Here you can find the source of _forEach(callback)

Method Source Code

'use strict';/*  www .  j a v  a  2s. c o  m*/

const testArray = ['Bob', 'Mary', 'Lee', 'Snake', 'Jimbob'];

Array.prototype._forEach = function(callback) {

  for (let i = 0; i < this.length; i++) {
    callback(this[i]);
  }
  return this;
};

// Simply console logging the array
testArray._forEach( item => {
  console.log(item);
});

// Splitting the array
testArray._forEach( item => {
  let newArray = item.split('');
  console.log(newArray);
  return newArray;
});

// Splitting and reversing the array
testArray._forEach( item => {
  let newArray = item.split('').reverse();
  console.log(newArray);
  return newArray;
});

// Adding the #1 to each item
testArray._forEach( item => {
  let newArray = [];
  newArray.push(item + 1);
  console.log(newArray);
  return newArray;
});

Related

  1. foreach( callback )
    Array.prototype.foreach = function( callback ) {
      for( var k=0; k<this .length; k++ ) {
        callback( k, this[ k ] );
    Object.prototype.foreach = function( callback ) {
      for( var k in this ) {
        if(this.hasOwnProperty(k)) {
         callback( k, this[ k ] );
    ...
    
  2. foreach(callback)
    Array.prototype.foreach = function(callback) {
      for(var i in this) if(this.hasOwnProperty(i)) callback(this[i]);
      return this;
    
  3. foreach(callback)
    Array.prototype.foreach = function(callback)
        for (var i = 0; i < this.length; i++)
            callback(this[i])
    Array.prototype.getRandomIndex = function()
        var n = Math.floor(Math.random()*this.length)
        return n
    Array.prototype.getRandomElement = function()
        var n = this.getRandomIndex()
        return this[n]
    var Arrays = {
        remove: function(obj, arr) {
            var index = arr.indexOf(obj);
            if (index != -1)
                arr.splice(index, 1);
        },
        contains: function(obj, arr) {
            return arr.indexOf(obj) > -1;
        },
        addIfAbsent: function(obj, arr) {
            if (!Arrays.contains(obj, arr)) {
                arr.push(obj);
        },
        getRandomElement: function(arr) {
          var n = this.getRandomIndex(arr);
          return arr[n];
        },
        getRandomIndex: function(arr) {
         var n = Math.floor((Math.random()*arr.length));
          return n;
    };
    
  4. foreach(fn)
    Array.prototype.foreach = function(fn) {
      for (let i = 0; i < len; i++)
        fn(this[i], i, this);
    };
    
  5. foreach(func)
    Array.prototype.foreach = function(func) {
        var length = this.length;
        for ( var i = 0; i < length; i++ ) {
            func(this[i]);
    };