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>

输出

单击“结果”按钮以四舍五入数字 −

更新于: 17-12-2019

93 次浏览

开启您的 职业 生涯

完成课程即可获得认证

开始学习
广告
© . All rights reserved.