Polyfill for push method in JavaScript

妖精的绣舞 提交于 2020-03-04 02:43:48

问题


In recent interview, interviewer has asked can you write polyfill for push() method in javascript.

any one know how to do this .?


回答1:


push() adds one or more elements at the end of array and returns new length of array. You can use array's length property to add element at the end of it.

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:


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


来源:https://stackoverflow.com/questions/31533963/polyfill-for-push-method-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!