數組的map()方法用於遍歷數組,每遍歷一個元素就調用回調方法一次,並將回調函數的返回結果作為新數組的元素,被遍歷的數組不會被改變。
語法:let newAarray = arr.map(function callback(currentValue, index, array) { // Return element for newArray }
示例:
let numbers = [1, 5, 10, 15]; let doubles = numbers.map((x) => { return x * 2; }); // doubles is now [2, 10, 20, 30] // numbers is still [1, 5, 10, 15] let numbers = [1, 4, 9]; let roots = numbers.map(Math.sqrt); // roots is now [1, 2, 3] // numbers is still [1, 4, 9]
參考博文:javascript map()方法解析