目录

map()

描述 (Description)

Javascript数组map()方法创建一个新数组,其结果是在此数组中的每个元素上调用提供的函数。

语法 (Syntax)

其语法如下 -

array.map(callback[, thisObject]);

参数细节 (Parameter Details)

  • callback - 从当前元素生成新Array的元素的函数。

  • thisObject - 执行回调时用作this对象的对象。

返回值 (Return Value)

返回创建的数组。

兼容性 (Compatibility)

此方法是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;
   };
}

例子 (Example)

请尝试以下示例。

<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>

输出 (Output)

roots is : 1,2,3  
↑回到顶部↑
WIKI教程 @2018