Roshin's blog Roshin's blog
首页
  • 《数据结构与算法》笔记
  • 手写代码
  • 实用方法
  • 文档教程
  • 面试集锦
  • 分类
  • 标签
  • 归档
  • 个人介绍
  • 关于博客
  • 友情链接
GitHub (opens new window)

Roshin

如果你只做自己能力范围之内的事情,就永远没法进步。
首页
  • 《数据结构与算法》笔记
  • 手写代码
  • 实用方法
  • 文档教程
  • 面试集锦
  • 分类
  • 标签
  • 归档
  • 个人介绍
  • 关于博客
  • 友情链接
GitHub (opens new window)
  • 手写代码

    • Array.prototype.map()
      • Array.prototype.map()
      • 语法
      • 参数
      • 返回值
      • 示例
      • 手写实现
    • Array.prototype.reduce()
    • Array.prototype.flat()
    • instanceof 运算符
  • 实用方法

  • JavaScript
  • 手写代码
roshin
2021-04-13

Array.prototype.map()

Array.prototype.map() #

map() 方法创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。

语法 #

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
  // Return element for new_array
}[, thisArg])
1
2
3

参数 #

  • callback: 生成新数组元素的函数,包含三个参数:
    • currentValue: 正在处理的当前元素
    • index(可选): 正在处理的当前元素的索引
    • array(可选): 调用 map() 的数组
  • thisArg(可选): 执行 callback 函数时的 this,注意如果 callback 是箭头函数无效

返回值 #

一个由原数组每个元素执行回调函数的结果组成的新数组。

示例 #

const numbers = [1, 4, 9];
const roots = numbers.map(Math.sqrt);

console.log(numbers); // [1, 4, 9]
console.log(roots); // [1, 2, 3]
1
2
3
4
5

手写实现 #

Array.prototype.myMap = function map(callback, thisArg) {
  // 首先判断传入的第一个参数是否为函数, 如果不是则抛出错误
  if (Object.prototype.toString.call(callback) !== '[object Function]') {
    throw '第一个参数必须是一个函数';
  }

  const array = this; // 拿到当前数组
  const result = []; // 定义一个空数组用作保存数据使用

  // 遍历, 调用传入的函数, 并将返回值保存在 result 中,注意这里将 this 指向改为 thisArg
  for (let i = 0; i < array.length; i++) {
    result.push(callback.call(thisArg, array[i], i, array));
  }

  return result;
};

const numbers = [1, 4, 9];
const roots = numbers.myMap(Math.sqrt);

console.log(numbers); // [1, 4, 9]
console.log(roots); // [1, 2, 3]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
编辑 (opens new window)
上次更新: 2021-06-23 08:43:55
Array.prototype.reduce()

Array.prototype.reduce()→

最近更新
01
函数柯里化
04-15
02
Array.prototype.flat()
04-14
03
Array.prototype.reduce()
04-14
更多文章>
Theme by Vdoing Copyright © 2021-present Roshin | MIT License | 粤ICP备18116277号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式