Home > Web Front-end > JS Tutorial > Javascript array polyfils: map, filter

Javascript array polyfils: map, filter

Patricia Arquette
Release: 2024-12-17 06:47:25
Original
268 people have browsed it

Javascript array polyfils: map, filter

What is polyfills in javascript?

In modern times, the latest version of JavaScript supports a wide range of features. However, some older browsers do not fully support all of these new features, which may cause your logic to not work as expected in browsers like Internet Explorer (IE).

To ensure compatibility with older browsers, you can write custom logic that mimics the behavior of these newer features. This custom code is known as a "polyfill."

In this post, I will provide you with a few examples of polyfills for array methods.

1. map:

    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);
      }
  }
Copy after login

In above code you can see I added one map method in array’s prototype chain if there is no native map method.

2. filter:

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);
    }
}
Copy after login

The above is the detailed content of Javascript array polyfils: map, filter. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template