Javascript 数组 polyfils:映射、过滤器

来源:undefined 2025-02-13 00:22:24 1017

什么是 javascript 中的 polyfill?

现代,最新版本的 javascript 支持广泛的功能。然而,一些较旧的浏览器并不完全支持所有这些新功能,这可能会导致您的逻辑在 internet explorer (ie) 等浏览器中无法按预期工作。

为了确保与旧版浏览器的兼容性,您可以编写模仿这些新功能的行为的自定义逻辑。此自定义代码称为“polyfill”。

在这篇文章中,我将为您提供一些数组方法的 polyfill 示例。

立即学习Java免费学习笔记(深入)”;

1。地图:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

if (!array.prototype.map) {

try {

array.prototype.map = function(callback) {

const arr = [];

if (typeof callback !== "function") {

throw new error("map callback is not a function");

} else {

const len = this.length;

for (let i = 0; i < len; i++) {

const val = callback(this[i], i);

arr.push(val);

}

}

return arr;

}

} catch (err) {

console.error(err);

}

}

登录后复制

在上面的代码中你可以看到,如果没有原生的map方法,我在数组的原型链中添加了一个map方法。

2。过滤器:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

if (!Array.prototype.filter) {

try {

Array.prototype.filter = function(callback) {

const arr = [];

if (typeof callback !== "function") {

throw new Error("filter callback is not a function");

} else {

const len = this.length;

for (let i = 0; i < len; i++) {

const val = callback(this[i], i);

if (val) {

arr.push(this[i]);

}

}

}

return arr;

}

} catch (err) {

console.error(err);

}

}

登录后复制

以上就是Javascript 数组 polyfils:映射、过滤器的详细内容,更多请关注php中文网其它相关文章!

最新文章