当前位置:首页 > JavaScript

js map方法 实现

2026-03-15 20:14:41JavaScript

map方法的基本概念

JavaScript中的map方法是数组对象的一个高阶函数,用于对数组中的每个元素执行指定操作并返回一个新数组。原数组不会被修改。

语法结构

const newArray = array.map(function(currentValue, index, arr) {
  // 返回处理后的元素
}, thisValue);
  • currentValue: 当前处理的数组元素
  • index(可选): 当前元素的索引
  • arr(可选): 正在操作的数组
  • thisValue(可选): 执行回调时使用的this

基本使用示例

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]

实现原理

map方法的Polyfill实现可以这样理解:

js map方法 实现

Array.prototype.myMap = function(callback, thisArg) {
  if (this == null) {
    throw new TypeError('Array.prototype.myMap called on null or undefined');
  }
  if (typeof callback !== 'function') {
    throw new TypeError(callback + ' is not a function');
  }

  const result = [];
  const array = Object(this);
  const len = array.length >>> 0;

  for (let i = 0; i < len; i++) {
    if (i in array) {
      result[i] = callback.call(thisArg, array[i], i, array);
    }
  }
  return result;
};

常见应用场景

处理对象数组提取特定属性:

js map方法 实现

const users = [
  {id: 1, name: 'Alice'},
  {id: 2, name: 'Bob'}
];
const names = users.map(user => user.name);
// ['Alice', 'Bob']

转换数据格式:

const temperatures = [
  {city: 'Tokyo', temp: 22},
  {city: 'London', temp: 14}
];
const formatted = temperatures.map(({city, temp}) => 
  `${city}: ${temp}°C`
);
// ['Tokyo: 22°C', 'London: 14°C']

注意事项

map方法会跳过空位但不会跳过undefinednull值。回调函数必须包含return语句,否则新数组将充满undefined

const arr = [1, 2, , 4];
const mapped = arr.map(x => x * 2);
// [2, 4, empty, 8]

性能考虑

对于大型数组,map可能不是最高效的选择,因为它会创建新数组。如果不需要新数组,forEach可能是更好的选择。现代JavaScript引擎已对map进行了高度优化,在大多数情况下性能差异可以忽略。

标签: 方法js
分享给朋友:

相关文章

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url, f…

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval 实…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-containe…

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…