Polyfill 是什么
Polyfill 是一种修改或添加新功能的方法。它基本上是一段代码,用于添加/修改新功能。它被用于为Web浏览器提供现代功能。
- 它基本上是用于为Web浏览器提供现代功能的一段代码。
- 它用于添加/修改新功能。
就像浏览器回退一样,如果你的浏览器没有提供map()函数,那么你就需要编写自己的map()函数。我们将讨论以下几种方法的Polyfill:
- 使用map()函数
- 使用forEach()函数
- 使用reduce()函数
我们将编写自己的map()、forEach()和reduce()函数。这些都是高阶函数,它们在 Array.prototype 中定义,以便对所有声明的数组都可访问。
要创建自己的Polyfill,我们需要将它们声明在 Array.prototype 中。
1. map()函数的Polyfill
示例: 我们已经给定一个数组,我们需要将每个元素乘以二。
Javascript
const arr = [1, 2, 3, 4, 5];
function callback(ele) {
return ele * 2;
}
Array.prototype.myMap = function (callback) {
const myArr = [];
for (const i in this) {
myArr.push(callback(this[i]));
}
return myArr;
};
const newArr = arr.myMap(callback);
for (i in newArr) {
console.log(newArr[i]);
}
输出:
2
4
6
8
10
2. forEach( ) 函数的 Polyfill
示例: 创建一个类似 JavaScript 中 forEach( ) 函数的自定义函数。
JavaScript
const arr = [1, 2, 3, 4, 5];
function myFunction(ele) {
console.log(ele);
}
Array.prototype.myForEach = function (callback) {
for (const i in this) {
callback(this[i]);
}
};
arr.myForEach(myFunction);
输出:
1
2
3
4
5
3. reduce() 函数的 Polyfill
示例: 找到给定数组中所有偶数的和。
Javascript
const arr = [1, 2, 3, 4, 5, 6];
function callback(ele) {
if (ele % 2 == 0) {
return true;
}
return false;
}
Array.prototype.myReduce = function (callback, sum) {
for (const i in this) {
if (callback(this[i])) {
sum += this[i];
}
}
return sum;
};
const sum = arr.myReduce(callback, 0);
console.log(sum);
输出:
12
参考: https://developer.mozilla.org/en-US/docs/Glossary/Polyfill
极客教程