JavaScript map方法
2012-08-28 15:25:14| 分類: JavaScript|字號 訂閱
map 方法 (JavaScript)
對數組的每個元素調用定義的回調函數並返回包含結果的數組。
對數組用指定的方法。
array1.map(callbackfn[, thisArg])
對於數組中的每個元素,map 方法都會調用 callbackfn 函數一次(采用升序索引順序)。 不為數組中缺少的元素調用該回調函數。
除了數組對象之外,map 方法可由具有 length 屬性且具有已按數字編制索引的屬性名的任何對象使用。
回調函數語法
回調函數的語法如下所示:
function callbackfn(value, index, array1)
可使用最多三個參數來聲明回調函數。
下表列出了回調函數參數。
| 回調參數 |
定義 |
|---|---|
| value |
數組元素的值。 |
| index |
數組元素的數字索引。 |
| array1 |
包含該元素的數組對象。 |
修改數組對象
數組對象可由回調函數修改。
下表描述了在 map 方法啟動后修改數組對象所獲得的結果。
下面的示例闡釋了 map 方法的用法。
// Define the callback function. function AreaOfCircle(radius) { var area = Math.PI * (radius * radius); return area.toFixed(0); } // Create an array. var radii = [10, 20, 30]; // Get the areas from the radii. var areas = radii.map(AreaOfCircle); document.write(areas); // Output: // 314,1257,2827
下面的示例闡釋 thisArg 參數的用法,該參數指定對其引用 this 關鍵字的對象。
// Define an object that contains a divisor property and // a remainder function. var obj = { divisor: 10, remainder: function (value) { return value % this.divisor; } } // Create an array. var numbers = [6, 12, 25, 30]; // Get the remainders. // The obj argument specifies the this value in the callback function. var result = numbers.map(obj.remainder, obj); document.write(result); // Output: // 6,2,5,0
在下面的示例中,內置 JavaScript 方法用作回調函數。
// Apply Math.sqrt(value) to each element in an array. var numbers = [9, 16]; var result = numbers.map(Math.sqrt); document.write(result); // Output: 3,4
map 方法可應用於字符串。 下面的示例闡釋了這一點。
// Define the callback function. function threeChars(value, index, str) { // Create a string that contains the previous, current, // and next character. return str.substring(index - 1, index + 2); } // Create a string. var word = "Thursday"; // Apply the map method to the string. // Each array element in the result contains a string that // has the previous, current, and next character. // The commented out statement shows an alternative syntax. var result = [].map.call(word, threeChars); // var result = Array.prototype.map.call(word, threeChars); document.write(result); // Output: // Th,Thu,hur,urs,rsd,sda,day,ay
