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 //defined the callback function 2 function showResult(val,index,arr){ 3 document.write("value:"+val); 4 document.write("index:"+index); 5 document.write("<br />"); 6 } 7 8 //defined an array and assignment two values 9 var arrays = ["hello","world"]; 10 11 //invoked 12 arrays.forEach(showResult) 13 14 //output 15 value:hello index:0 16 value:world index:1
map():
對數組的每個元素調用定義的回調函數并返回包含結果的數組.
注意:用法,參數和forEach()相似,但是map()要返回一個結果數組.參考上面forEach()的用法.直接上源碼:
// Production steps of ECMA-262, Edition 5, 15.4.4.19 // Reference: http://es5.github.io/#x15.4.4.19 if (!Array.prototype.map) { Array.prototype.map = function(callback, thisArg) { var T, A, 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 A be a new array created as if by the expression new Array(len) // where Array is the standard built-in constructor with that name and // len is the value of len. A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { var kValue, mappedValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal // method of O with argument Pk. kValue = O[k]; // ii. Let mappedValue be the result of calling the Call internal // method of callback with T as the this value and argument // list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments // Pk, Property Descriptor // { Value: mappedValue, // Writable: true, // Enumerable: true, // Configurable: true }, // and false. // In browsers that support Object.defineProperty, use the following: // Object.defineProperty(A, k, { // value: mappedValue, // writable: true, // enumerable: true, // configurable: true // }); // For best browser support, use the following: A[k] = mappedValue; } // d. Increase k by 1. k++; } // 9. return A return A; }; }
具體實現:
1 //defined callback function 2 function AreaOfCircle(radius){ 3 var res = Math.PI(radius*radius); 4 return res.toFixed(0); 5 } 6 7 //defined the array and assignment 8 var arr = [10,20,30]; 9 10 //invoked 11 var arrlist = arr.map(AreaOfCircle); 12 13 //output 14 document.write(arrlist); 15 16 314,1257,2827
filter():
返回數組中的滿足回調函數中指定的條件的元素.
filter()方法的參數也如上,不過區別在于它返回一個包含回調函數為其返回 true 的所有值的新數組。 如果回調函數為 array1 的所有元素返回 false,則新數組的長度為 0。
prototype源碼:
1 if (!Array.prototype.filter) { 2 Array.prototype.filter = function(fun/*, thisArg*/) { 3 'use strict'; 4 5 if (this === void 0 || this === null) { 6 throw new TypeError(); 7 } 8 9 var t = Object(this); 10 var len = t.length >>> 0; 11 if (typeof fun !== 'function') { 12 throw new TypeError(); 13 } 14 15 var res = []; 16 var thisArg = arguments.length >= 2 ? arguments[1] : void 0; 17 for (var i = 0; i < len; i++) { 18 if (i in t) { 19 var val = t[i]; 20 21 // NOTE: Technically this should Object.defineProperty at 22 // the next index, as push can be affected by 23 // properties on Object.prototype and Array.prototype. 24 // But that method's new, and collisions should be 25 // rare, so use the more-compatible alternative. 26 if (fun.call(thisArg, val, i, t)) { 27 res.push(val); 28 } 29 } 30 } 31 32 return res; 33 }; 34 }
具體實現:
1 // Define a callback function. 2 function CheckIfPrime(value, index, ar) { 3 high = Math.floor(Math.sqrt(value)) + 1; 4 5 for (var div = 2; div <= high; div++) { 6 if (value % div == 0) { 7 return false; 8 } 9 } 10 return true; 11 } 12 13 // Create the original array. 14 var numbers = [31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53]; 15 16 // Get the prime numbers that are in the original array. 17 var primes = numbers.filter(CheckIfPrime); 18 19 document.write(primes); 20 // Output: 31,37,41,43,47,53
以上資料整理官方文檔和javascript權威指南
文章列表