Polyfill for push method in JavaScript

In a recent interview, the interviewer asked if you could write a polyfill for a push()method in javascript.

Does anyone know how to do this.

+1
source share
2 answers

push()adds one or more elements at the end arrayand returns a new lengtharray. You can use the array property lengthto add an element to the end.

if (!Array.prototype.push) {
// Check if not already supported, then only add. No need to check this when you want to Override the method

    // Add method to prototype of array, so that can be directly called on array
    Array.prototype.push = function() {

        // Use loop for multiple/any no. of elements
        for (var i = 0; i < arguments.length; i++) {
            this[this.length] = arguments[i];
        }


        // Return new length of the array
        return this.length;
    };
}
+2
source

if (!Array.prototype.push) {
  Array.prototype.push = function () {
    for (var i = 0, len = arguments.length; i < len; i++) {
      this[this.length] = arguments[i];
      if (Object.prototype.toString.call(this).slice(8, -1).toLowerCase() === 'object') {
        this.length += 1;
      }
    }
    return this.length;
  };
}
Run codeHide result
0
source

Source: https://habr.com/ru/post/1657012/


All Articles