Javascript Array forEach() Method

Description:

Javascript array forEach() method calls a function for each element in the array.

Syntax:

array.forEach(callback[, thisObject]);

Here is the detail of parameters:

  • callback : Function to test each element of the array.

  • thisObject : Object to use as this when executing callback.

Return Value:

Returns created array.

Compatibility:

This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work you need to add following code at the top of your script:

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}


Example:

<html>
<head>
<title>JavaScript Array forEach Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}

function printBr(element, index, array) {
  document.write("<br />[" + index + "] is " + element ); 
}

[12, 5, 8, 130, 44].forEach(printBr);
  
</script>
</body>
</html>


This will produce the follow result:

[0] is 12
[1] is 5
[2] is 8
[3] is 130
[4] is 44 




reference:

http://www.tutorialspoint.com/javascript/array_foreach.htm


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值