ECMAScript 五 Array Methods(学习笔记)
ECMAScript 5 定义了9个新的数组方法,分别为:
1.forEach(); 2.map(); 3.filter(); 4.every(); 5.some(); 6.reduce(); 7.reduceRight(); 8.indexOf(); 9.lastIndexOf();
概述:首先,大多数的方法都接受一个函数作为第一个参数,并为数组里的每个元素(或者一些元素)执行这个函数.在稀疏数组中(索引不以0开始,并且元素不连续),不存在的数组元素不调用函数参数.大多数实例中,定义的函数(方法中的参数)包含三个参数:第一个是元素的值,第二个是元素的索引,第三个是数组本身.ECMAScript 5 数组方法不改变调用它们的数组,但是我们自己定义的函数可能会改变数组的值.接下来分别介绍具体方法:
forEach():
为数组中的每个元素执行指定操作.
array1.forEach(callbackfn[, thisArg])
参数:
参数 |
定义 |
---|---|
array1 |
必选。 一个数组对象。 |
callbackfn |
必选。 最多可以接受三个参数的函数。 对于数组中的每个元素,forEach 都会调用 callbackfn 函数一次。 |
thisArg |
可选。 callbackfn 函数中的 this 关键字可引用的对象。 如果省略 thisArg,则 undefined 将用作 this 值。 |
参数
如果callback参数不是函数对象,则将引发TypeError异常.
备注:
对于数组中出现的每个元素,forEach 方法都会调用 callbackfn 函数一次(采用升序索引顺序)。 将不会为数组中缺少的元素调用回调函数。
除了数组对象之外,forEach 方法可由具有 length 属性且具有已按数字编制索引的属性名的任何对象使用。
回调函数语法:
function callbackfn(value, index, array1)
你可使用最多三个参数来声明回调函数。
prototype源码: (来源于官方文档)
1 // Production steps of ECMA-262, Edition 5, 15.4.4.18 2 // Reference: http://es5.github.io/#x15.4.4.18 3 if (!Array.prototype.forEach) { 4 5 Array.prototype.forEach = function(callback, thisArg) { 6 7 var T, k; 8 9 if (this == null) { 10 throw new TypeError(' this is null or not defined'); 11 } 12 13 // 1. Let O be the result of calling ToObject passing the |this| value as the argument. 14 var O = Object(this); 15 16 // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". 17 // 3. Let len be ToUint32(lenValue). 18 var len = O.length >>> 0; 19 20 // 4. If IsCallable(callback) is false, throw a TypeError exception. 21 // See: http://es5.github.com/#x9.11 22 if (typeof callback !== "function") { 23 throw new TypeError(callback + ' is not a function'); 24 } 25 26 // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. 27 if (arguments.length > 1) { 28 T = thisArg; 29 } 30 31 // 6. Let k be 0 32 k = 0; 33 34 // 7. Repeat, while k < len 35 while (k < len) { 36 37 var kValue; 38 39 // a. Let Pk be ToString(k). 40 // This is implicit for LHS operands of the in operator 41 // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk. 42 // This step can be combined with c 43 // c. If kPresent is true, then 44 if (k in O) { 45 46 // i. Let kValue be the result of calling the Get internal method of O with argument Pk. 47 kValue = O[k]; 48 49 // ii. Call the Call internal method of callback with T as the this value and 50 // argument list containing kValue, k, and O. 51 callback.call(T, kValue, k, O); 52 } 53 // d. Increase k by 1. 54 k++; 55 } 56 // 8. return undefined 57 }; 58 }
具体应用如下:
1 //定义回调函数 2 function showResult(val,index,arr){ 3 document.write("value:"+val); 4 document.write("index:"+index); 5 document.write("<br />"); 6 } 7 8 //定义数组 9 var arrays = ["hello","world"]; 10 11 //调用forEach() 12 arrays.forEach(showResult) 13 14 //输出 15 value:hello index:0 16 value:world index:1