javascript数组forEach方法
forEach 方法 (JavaScript)
备注:IE8-浏览器不支持,需要扩展
IE9+,firefox1.5+,chrome浏览器才支持数组的forEach方法,// 说明:Javascript Array 的 forEach 方法 // 整理:http://www.CodeBit.cn // 来源:http://developer.mozilla.org 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); } }; }
为数组中的每个元素执行指定操作。使用方法:array1.forEach(callbackfn[, thisArg])
对于数组中的每个元素,forEach 方法都会调用 callbackfn 函数一次(采用升序索引顺序)。 不为数组中缺少的元素调用该回调函数。
除了数组对象之外,forEach 方法可由具有 length 属性且具有已按数字编制索引的属性名的任何对象使用。
回调函数语法
回调函数的语法如下所示:
function callbackfn(value, index, array1)
可使用最多三个参数来声明回调函数。
回调函数的参数如下所示。
回调参数 |
定义 |
---|---|
value |
数组元素的值。 |
index |
数组元素的数字索引。 |
array1 |
包含该元素的数组对象。 |
修改数组对象
forEach 方法不直接修改原始数组,但回调函数可能会修改它。 下表描述了在 forEach 方法启动后修改数组对象所获得的结果。
forEach 方法启动后的条件 |
元素是否传递给回调函数 |
---|---|
在数组的原始长度之外添加元素。 |
否。 |
添加元素以填充数组中缺少的元素。 |
是,如果该索引尚未传递给回调函数。 |
元素被更改。 |
是,如果该元素尚未传递给回调函数。 |
从数组中删除元素。 |
否,除非该元素已传递给回调函数。 |
下面的示例阐释了 forEach 方法的用法。
<script>// Define the callback function. function ShowResults(value, index, ar) { document.write("value: " + value); document.write(" index: " + index); document.write("<br />"); } // Create an array. var letters = ['ab', 'cd', 'ef']; // Call the ShowResults callback function for each // array element. letters.forEach(ShowResults); // Output: // value: ab index: 0 // value: cd index: 1 // value: ef index: 2 </script>
在下面的示例中,callbackfn 参数包含回调函数的代码。
<script>// Create an array. var numbers = [10, 11, 12]; // Call the addNumber callback function for each array element. var sum = 0; numbers.forEach( function addNumber(value) { sum += value; } ); document.write(sum); // Output: 33</script>
下面的示例阐释了 thisArg 参数的用法,该参数指定可对其引用 this 关键字的对象。
<script>// Define the object that contains the callback function. var obj = { showResults: function(value, index) { // Call calcSquare by using the this value. var squared = this.calcSquare(value); document.write("value: " + value); document.write(" index: " + index); document.write(" squared: " + squared); document.write("<br />"); }, calcSquare: function(x) { return x * x } }; // Define an array. var numbers = [5, 6]; // Call the showResults callback function for each array element. // The obj is the this value within the // callback function. numbers.forEach(obj.showResults, obj); // Embed the callback function in the forEach statement. // The obj argument is the this value within the obj object. // The output is the same as for the previous statement. numbers.forEach(function(value, index) { this.showResults(value, index) }, obj); // Output: // value: 5 index: 0 squared: 25 // value: 6 index: 1 squared: 36 // value: 5 index: 0 squared: 25 // value: 6 index: 1 squared: 36</script>
来源:http://msdn.microsoft.com/zh-cn/library/ff679980%28v=vs.94%29.aspx
加支付宝好友偷能量挖...