一、map
**语法**: array.map(function(currentValue,index,arr), thisValue)
**参数说明**
currentValue: 必须,当前元素的值
index: 可选,当前元素的索引值
arr: 可选,当前元素属于的数组对象
thisValue: 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。
**返回值**: 返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值
手写实现
Array.prototype.myMap = function (fn, thisValue) {
if (typeof fn !== 'function') {
throw new Error(`${fn} 不是一个函数`)
}
if ([null, undefined].includes(this)) {
throw new Error(`this 是null 或者 undefined`)
}
// 在非严格模式下使用改变this指向都会包装成一个对象,但在严格模式下则不会包装
const arr = Object(this)
let res = []
for (let i = 0; i < arr.length; i++) {
res[i] = fn.call(thisValue, arr[i], i, arr)
}
return res
}
二、forEach
**语法**:array.forEach(function(currentValue, index, arr),thisValue)
**参数说明**
currentValue: 必须,当前元素的值
index: 可选,当前元素的索引值
arr: 可选,当前元素属于的数组对象
*thisValue*: 可选。传递给函数的值一般用 "this" 值。如果这个参数为空, "undefined" 会传递给 "this" 值
**返回值**: undefined
手写实现
Array.prototype.myForEach = function (fn, thisValue) {
if (typeof fn !== 'function') {
throw new Error(`${fn} 不是一个函数`)
}
if ([null, undefined].includes(this)) {
throw new Error(`this 是null 或者 undefined`)
}
const arr = Object(this)
for (let i = 0; i < arr.length; i++) {
fn.call(thisValue, arr[i], i, arr)
}
}
map和forEach区别
- forEach()返回值是undefined,不可以链式调用
- map()返回一个新数组,原数组不会改变