Rumah  >  Artikel  >  hujung hadapan web  >  javascript forEach() 方法讲解

javascript forEach() 方法讲解

WBOY
WBOYasal
2016-06-01 09:54:271648semak imbas

<strong>forEach()</strong>方法让数组的每一项都执行一次给定的函数。

<strong>forEach()基本语法</strong>

<code class="language-javascript">array.forEach(callback[, thisArg])</code>

 

<strong>forEach()参数介绍</strong>

参数名 介绍
callback

在数组每一项上执行的函数,接收三个参数:

  • currentValue 当前项(指遍历时正在被处理那个数组项)的值。
  • index 当前项的索引(或下标)。
  • array 数组本身。
thisArg 可选参数。用来当作callback 函数内this的值的对象。

 

<strong>forEach()功能说明:</strong>

forEach 方法按升序为数组中含有效值的每一项执行一次callback 函数,那些已删除(使用delete方法等情况)或者从未赋值的项将被跳过(但不包括哪些值为 undefined 的项)。

callback 函数会被依次传入三个参数:

  • 数组当前项的值
  • 数组当前项的索引
  • 数组对象本身

如果给forEach传递了thisArg 参数,它将作为 callback 函数的执行上下文,类似执行如下函数callback.call(thisArg, element, index, array)。如果 thisArg 值为 undefined 或 null,函数的this 值取决于当前执行环境是否为严格模式(严格模式下为 undefined,非严格模式下为全局对象)。

forEach 遍历的范围在第一次调用 callback 前就会确定。调用forEach 后添加到数组中的项不会被 callback 访问到。如果已经存在的值被改变,则传递给 callback 的值是 forEach 遍历到他们那一刻的值。已删除的项不会被遍历到。

注意: 没有办法中止或者跳出 forEach 循环,除了抛出一个异常。如果你需要这样,使用forEach()方法是错误的,你可以用一个简单的循环作为替代。如果您正在测试一个数组里的元素是否符合某条件,且需要返回一个布尔值,那么可使用 Array.every 或 Array.some

forEach 为数组中的元素执行一次 callback 函数,不像 every 和 some,它总是返回 undefined

 

<strong>forEach()实例一:</strong>打印出数组的内容​

下面的代码会为每一个数组元素输出一行记录:

<code class="language-javascript">function logArrayElements(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9</code>

 

<strong>forEach()实例二:</strong>对象复制函数​

下面的代码会创建一个给定对象的副本。 创建对象的副本有不同的方法,以下是只是一种方法,并解释了Array.prototype.forEach() 是如何使用ECMAScript 5 Object.* 元属性(meta property )函数工作的。

<code class="language-javascript">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 looks like o1 now</code>

 

forEach()兼容旧环境

forEach 是在第五版本里被添加到 ECMA-262 标准的;这样它可能在标准的其他实现中不存在,你可以在你调用 forEach 之前 插入下面的代码,在本地不支持的情况下使用 forEach()。该算法是 ECMA-262 第5版中指定的算法。算法假定ObjectTypeError拥有它们的初始值。callback.call 等价于Function.prototype.call()

<code class="language-javascript">// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.com/#x15.4.4.18
if ( !Array.prototype.forEach ) {

  Array.prototype.forEach = function forEach( callback, thisArg ) {

    var T, k;

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

    // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0; 

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

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if ( arguments.length > 1 ) {
      T = thisArg;
    }

    // 6. Let k be 0
    k = 0;

    // 7. Repeat, while k </code>

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn