foreach()方法让数组的每一项都执行一次给定的函数。
foreach()基本语法
array.foreach(callback[, thisarg])
foreach()参数介绍
参数名 介绍
callback 在数组每一项上执行的函数,接收三个参数:
currentvalue 当前项(指遍历时正在被处理那个数组项)的值。 index 当前项的索引(或下标)。 array 数组本身。
thisarg 可选参数。用来当作callback 函数内this的值的对象。
foreach()功能说明:
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。
foreach()实例一:打印出数组的内容
下面的代码会为每一个数组元素输出一行记录:
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
foreach()实例二:对象复制函数
下面的代码会创建一个给定对象的副本。 创建对象的副本有不同的方法,以下是只是一种方法,并解释了array.prototype.foreach() 是如何使用ecmascript 5 object.* 元属性(meta property )函数工作的。
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
foreach()兼容旧环境
foreach 是在第五版本里被添加到 ecma-262 标准的;这样它可能在标准的其他实现中不存在,你可以在你调用 foreach 之前 插入下面的代码,在本地不支持的情况下使用 foreach()。该算法是 ecma-262 第5版中指定的算法。算法假定object和typeerror拥有它们的初始值。callback.call 等价于function.prototype.call()。
// production steps of ecma-262, edition 5, 15.4.4.18// reference: http://es5.github.com/#x15.4.4.18if ( !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