在这篇博客中,我们将了解如何 ,并通过为它们编写 polyfils 来工作。map
filter
reduce
polyfill 是一段代码(通常是 Web 上的 JavaScript),用于在本机不支持它的旧浏览器上提供现代功能。
map()
方法创建并返回一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。
参数
返回值
const array = [1, 2, 3, 4]; // pass a function to map const mapResult = array.map(x => x * 2); console.log(mapResult); // output: Array [2, 4, 6, 8]
让我们通过为 编写一个 polyfill 来理解这一点。map
Array.prototype.myMap = function (callbackFunction) { let newArray = [] for ( let i = 0; i < this.length; i++ ) { newArray.push(callbackFunction(this[i], i, this)) } return newArray }
该方法创建一个新数组,其中填充了传递提供的回调的元素。它创建给定数组的一部分的浅拷贝,过滤到给定数组中通过提供的回调函数实现的测试的元素。filter()
参数
返回值
const array = [1, 2, 3, 4]; // pass a function to filter const filterResult = array.map(x => x > 2); console.log(filterResult); // output: Array [1,2]
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"]
让我们通过编写一个 polyfill 来理解这一点filter
Array.prototype.myFilter = function (callbackFunction) { let newArray = [] for ( let i = 0; i < this.length; i++ ) { if(callbackFunction(this[i], i, this)) { newArray.push(this[i]) } } return newArray }
reduce()
方法按顺序对数组的每个元素执行“reducer”回调函数,传入前一个元素计算的返回值。跨数组的所有元素运行化简器的最终结果是单个值。
第一次运行回调时,没有“上一次计算的返回值”。如果提供,可以使用初始值代替它。否则,索引 0 处的数组元素用作初始值,迭代从下一个元素(索引 1 而不是索引 0)开始。
让我们通过添加数字数组来理解这一点
const array = [1, 2, 3, 4]; const initialValue = 0; const reducer = (previousValue, currentValue) => previousValue + currentValue // 0 + 1 + 2 + 3 + 4 const sum = array.reduce(reducer,initialValue); console.log(sum); // expected output: 10
参数
返回值
让我们通过编写一个 polyfill 来理解这一点reduce
Array.prototype.myReduce = function (reducerCallback, initialValue) { let accumulator = initialValue for ( let i = 0; i < this.length; i++ ) { accumulator = accumulator ? reducerCallback(accumulator, this[i], i, this) : this[0] } return accumulator }
两者都是允许我们循环遍历数组并执行回调函数的方法。map
forEach
和之间的主要区别在于map返回一个数组,但forEach不返回。map
forEach
const array = [1,2,3,4,5] const mapResult = array.map(x => x + 1) const forEachResult = array.forEach(x => x + 1) console.log(mapResult) // [2,3,4,5,6] console.log(forEachResult) // undefined
forEach 回调函数仍在运行,但它只是不返回任何内容,它返回undefined.
map()
方法创建并返回一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。filter()
reduce()
方法按顺序对数组的每个元素执行“reducer”回调函数,传入前一个元素计算的返回值。跨数组的所有元素运行化简器的最终结果是单个值。map
forEach
map
forEach