[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach [Back]  [Original]

Array.prototype.forEach() - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

Array.prototype.forEach()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 ..

forEach() .

In this article

const array1 = ["a", "b", "c"];

array1.forEach((element) => console.log(element));

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"

arr.forEach(function callback(currentValue, index, array) {
    //your iterator
}[, thisArg]);

callback

, . :

currentValue

.

index

.

array

, .

thisArg

. , this callback.

undefined.

forEach() callback , . . , , undefined.

callback :

  • (value)
  • (index)
  • , (array)

forEach() thisArg, callback this. , this undefined. , this, callback, this, .

, forEach(), callback. , forEach(), callback. , , callback, , forEach() ; . (, shift()), . ( )

( )

js
const arraySparse = [1, 3, , 7];
let numCallbackRuns = 0;

arraySparse.forEach((element) => {
  console.log(element);
  numCallbackRuns++;
});

console.log("numCallbackRuns: ", numCallbackRuns);

// 1
// 3
// 7
// numCallbackRuns: 3
// :       3  7    callback.

for forEach

js
const items = ["item1", "item2", "item3"];
const copy = [];

// 
for (let i = 0; i < items.length; i++) {
  copy.push(items[i]);
}

// 
items.forEach(function (item) {
  copy.push(item);
});

: console.table(), .

, forEach().

:

js
function logArrayElements(element, index, array) {
  console.log("a[" + index + "] = " + element);
}

//       2,   ,    
[2, 5, , 9].forEach(logArrayElements);
// :
// a[0] = 2
// a[1] = 5
// a[3] = 9

thisArg

() , :

js
function Counter() {
  this.sum = 0;
  this.count = 0;
}
Counter.prototype.add = function (array) {
  array.forEach((entry) => {
    this.sum += entry;
    ++this.count;
  }, this);
  // ^---- Note
};

const obj = new Counter();
obj.add([2, 5, 9]);
obj.count;
// 3
obj.sum;
// 16

forEach() thisArg (this), callback . callback this.

: callback , thisArg , this.

Array.prototype.every() THRESHOLD.

js
var THRESHOLD = 12;
var v = [5, 2, 16, 4, 3, 18, 20];
var res;

res = v.every(function (element, index, array) {
  console.log("element:", element);
  if (element >= THRESHOLD) {
    return false;
  }

  return true;
});
console.log("res:", res);
// :
// element: 5
// element: 2
// element: 16
// res: false

res = v.some(function (element, index, array) {
  console.log("element:", element);
  if (element >= THRESHOLD) {
    return true;
  }

  return false;
});
console.log("res:", res);
// :
// element: 5
// element: 2
// element: 16
// res: true

. , . , Array.prototype.forEach(), - Object.* ECMAScript 5.

js
function copy(o) {
  var copy = Object.create(Object.getPrototypeOf(o));
  var propNames = Object.getOwnPropertyNames(o);

  propNames.forEach(function (name) {
    var desc = Object.getOwnPropertyDescriptor(o, name);
    Object.defineProperty(copy, name, desc);
  });

  return copy;
}

var o1 = { a: 1, b: 2 };
var o2 = copy(o1); //  o2  ,   o1

"one", "two", "four".

, 'two', , . 'four' , 'three' .

forEach() .

js
let words = ["one", "two", "three", "four"];
words.forEach((word) => {
  console.log(word);
  if (word === "two") {
    words.shift();
  }
});
// one
// two
// four

()

. , Array.prototype.flat()

js
function flatten(arr) {
  const result = [];

  arr.forEach((i) => {
    if (Array.isArray(i)) {
      result.push(...flatten(i));
    } else {
      result.push(i);
    }
  });

  return result;
}

// Usage
const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]];

flatten(nested); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

forEach() ECMA-262 5- ; . , , forEach() , . , ECMA-262 5- ; , Object TypeError callback.call Function.prototype.call().

js
//   ECMA-262, 5- , 15.4.4.18
//  (en): http://es5.github.io/#x15.4.4.18
//  (ru): http://es5.javascript.ru/x15.4.html#x15.4.4.18
if (!Array.prototype.forEach) {
  Array.prototype.forEach = function (callback, thisArg) {
    var T, k;

    if (this == null) {
      throw new TypeError(" this is null or not defined");
    }

    // 1.  O    ToObject passing the |this| value as the argument.
    var O = Object(this);

    // 2.  lenValue      Get  O   "length".
    // 3.  len  ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4.  IsCallable(callback)  false,   TypeError.
    // : http://es5.github.com/#x9.11
    if (typeof callback !== "function") {
      throw new TypeError(callback + " is not a function");
    }

    // 5.  thisArg ,  T  thisArg;   T  undefined.
    if (arguments.length > 1) {
      T = thisArg;
    }

    // 6.  k  0
    k = 0;

    // 7.  k < len,  
    while (k < len) {
      var kValue;

      // a.  Pk  ToString(k).
      //           in
      // b.  kPresent      HasProperty  O   Pk.
      //          c
      // c.  kPresent  true, 
      if (k in O) {
        // i.  kValue      Get  O   Pk.
        kValue = O[k];

        // ii.    Call  callback   T    this 
        //  ,  kValue, k  O.
        callback.call(T, kValue, k, O);
      }
      // d.  k  1.
      k++;
    }
    // 8.  undefined.
  };
}

Specification
ECMAScript 2027 LanguageSpecification
# sec-array.prototype.foreach


Web Proxy Viewer  |  New URL  |  Original Page