Array对象允许在一个变量中存储多个值。它存储相同类型元素的固定大小的顺序集合。数组用于存储数据集合,但将数组看作同一类型变量的集合通常更有用。本文主要介绍JavaScript(JS) array.map(callback[, thisObject]) 方法。

1、描述

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

2、语法

它的语法如下:

array.map(callback[, thisObject]);

3、参数

  • callback:从当前元素生成新数组元素的函数。
  • thisObject: this对象在执行回调时使用。

4、返回值

返回创建的数组。

5、兼容性

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

6、使用示例

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

7、输出

roots is : 1,2,3  

推荐文档

相关文档

大家感兴趣的内容

随机列表