Latest web development tutorials

JavaScript Array map() 方法

Array 對象參考手冊 JavaScript Array對象

實例

返回一個數組,數組中元素為原始數組的平方根:

var numbers = [ 4 , 9 , 16 , 25 ];

function myFunction() {
x = document.getElementById( "demo" )
x.innerHTML = numbers.map(Math.sqrt);
}

輸出結果為:

2,3,4,5

嘗試一下»

定義和用法

map() 方法返回一個新數組,數組中的元素為原始數組元素調用函數處理後的值。

map() 方法按照原始數組元素順序依次處理元素。

注意: map()不會對空數組進行檢測。

注意: map()不會改變原始數組。


瀏覽器支持

表格中的數字表示支持該方法的第一個瀏覽器的版本號。

方法
map() Yes 9 1.5 Yes Yes

語法

array.map(function(currentValue,index,arr), thisValue)

參數說明

參數 描述
function(currentValue, index,arr) 必須。 函數,數組中的每個元素都會執行這個函數函數參數:
參數 描述
currentValue 必須。 當前元素的值
index 可選。 當期元素的索引值
arr 可選。 當期元素屬於的數組對象
thisValue 可選。 對像作為該執行回調時使用,傳遞給函數,用作"this" 的值。
如果省略了thisValue ,"this" 的值為"undefined"

技術細節

返回值: 返回一個新數組,數組中的元素為原始數組元素調用函數處理後的值。
JavaScript 版本: 1.6

更多實例

實例

數組中的每個元素乘於輸入框指定的值,並返回新數組:

var numbers = [ 65 , 44 , 12 , 4 ];

function multiplyArrayElement(num) {
return num * document.getElementById( "multiplyWith" ).value;
}

function myFunction() {
document.getElementById( "demo" ).innerHTML = numbers.map(multiplyArrayElement);
}

嘗試一下»

Array 對象參考手冊 JavaScript Array對象