JavaScript 数组 map() 方法
描述
Javascript 数组的 map() 方法将调用提供的函数对数组中的每个元素进行操作,并返回一个由操作结果组成的新数组。
语法
其语法如下所示 −
array.map(callback[, thisObject]);
参数详情
- callback − 从当前数组的元素生成新数组元素的函数。
 - 
thisObject − 执行回调函数时要使用的对象。
 
返回值
返回创建的数组。
兼容性
该方法是ECMA-262标准的JavaScript扩展,因此在标准的其他实现中可能不存在。要使其工作,您需要在脚本的顶部添加以下代码。
if (!Array.prototype.map) {
   Array.prototype.map = function(fun /*, thisp*/) {
      var len = this.length;
      if (typeof fun != "function")
      throw new TypeError();
      var res = new Array(len);
      var thisp = arguments[1];
      for (var i = 0; i < len; i++) {
         if (i in this)
         res[i] = fun.call(thisp, this[i], i, this);
      }
      return res;
   };
}
示例
尝试下面的示例。
<html>
   <head>
      <title>JavaScript Array map Method</title>
   </head>
   <body>
      <script type = "text/javascript">
         if (!Array.prototype.map) {
            Array.prototype.map = function(fun /*, thisp*/) {
               var len = this.length;
               if (typeof fun != "function")
               throw new TypeError();
               var res = new Array(len);
               var thisp = arguments[1];
               for (var i = 0; i < len; i++) {
                  if (i in this)
                  res[i] = fun.call(thisp, this[i], i, this);
               }
               return res;
            };
         }
         var numbers = [1, 4, 9];
         var roots = numbers.map(Math.sqrt);
         document.write("roots is : " + roots ); 
      </script>      
   </body>
</html>
输出
roots is : 1,2,3
极客教程