JavaScript Array.prototype.map() 函式
JavaScript 中的 Array.prototype.map() 函式用於建立一個新陣列,其中包含被呼叫函式的結果。
語法如下 −
arr.map(function callback(currentValue[, index[, array]])
現在,讓我們在 JavaScript 中實現 Array.prototype.map() 方法 −
示例
<!DOCTYPE html>
<html>
<body>
<h2>Demo Heading</h2>
<p>Click to display the abs() result...</p>
<button onclick="display()">Result</button>
<p id="test"></p>
<script>
function display() {
var arr = [1, -2, 3, 4, 5, -6, 7, 8, 9, 10];
var res = arr.map(Math.abs);
document.write(res);
}
</script>
</body>
</html>輸出

單擊上面的“結果”按鈕 −

示例
<!DOCTYPE html>
<html>
<body>
<h2>Demo Heading</h2>
<p>Click to round the numbers...</p>
<button onclick="display()">Result</button>
<p id="test"></p>
<script>
var arr = [11.4, 12.9, 25.6, 88.9];
document.getElementById("test").innerHTML = arr
function display() {
var res = arr.map(Math.round);
document.getElementById("test").innerHTML = res
}
</script>
</body>
</html>輸出

單擊“結果”按鈕以四捨五入數字 −

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP