JavaScript数组map()方法详解与兼容性处理

作者:代码拾荒时间:2026-10-29 10:46:59浏览:549

本文详细介绍JavaScript中Array对象的map()方法,该方法用于创建一个新数组,其结果是调用提供函数的结果。文章解析了callback和thisObject参数,并针对不支持ECMA-262标准的旧版浏览器提供了Polyfill兼容代码实现。

map()方法概述与语法

JavaScript中的数组map()方法会创建一个新数组,该新数组的元素是原数组中每个元素调用指定回调函数后的返回值。


array.map(callback[, thisObject]);

参数详解

该方法的语法结构如下:

  • 以下是参数的详细说明:
  • callback:用于生成新数组元素的函数,接收当前元素、索引和原数组作为参数。

thisObject:可选参数,指定回调函数执行时的this值。

返回值:返回一个由回调函数处理后的新数组。

浏览器兼容性处理

这种方法是一个JavaScript扩展到ECMA-262标准;因此它可能不存在在标准的其他实现。为了使它工作,你需要添加下面的脚本代码在顶部:


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

实例演示

map()方法是ECMA-262标准中定义的JavaScript扩展,因此在某些旧版或非标准的浏览器实现中可能不可用。为了确保兼容性,需要在代码顶部添加以下Polyfill脚本:


<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 

作者最新文章