笔试题:用reduce实现map——JavaScript

本文探讨如何使用reduce实现map方法。介绍了reduce的基本用法,包括其参数、初始值设定及thisArg的作用,并强调在箭头函数中this的指向问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,先看看map和reduce的完整用法:

arr.reduce((previousValue, currentValue, currentIndex, array) => {}, initialValue?)

reduce 接收两个参数,第一个参数为函数,指定了每次迭代调用的函数,函数的返回值为下一次迭代的 previousValue;第二个参数为初始值,是可选的。

若不指定初始值,那么第一次迭代的 previousValue 为 ar[[0], currentValue 为 arr[1], currentIndex 为 1,

若指定初始值,那么第一次迭代的 previousValue 为 initialValue, currentValue为 arr[0], currentIndex 为0.

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

其中第二个参数为 thisArg, 可选的,表示执行callback时的this。

注意,如果callback为箭头函数时,里面的this指向外层代码块,(非严格模式下为window),此时指定 thisArg 无效。

实现

/**
 * 用数组的reduce方法实现数组的map
 */
Array.prototype._map = function(fn, thisArg) {
  const result = [];
  this.reduce((prev, curr, index, array) => {
    result[index] = fn.call(thisArg, array[index], index, array);
  }, 0)
  return result;
}

// 使用reduce将数组的每个元素+索引值
const arr = [1,2,3,4,5]
const arr2 = [6,7,8]

const _mapArr = arr._map(function(v, i){
  return v+i+this.length;
}, arr2)

console.log(_mapArr);
// [4, 6, 8, 10, 12]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的桐人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值