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); } }
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); } }
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!