用于JavaScript的推送方法的Polyfill

时间:2015-07-21 08:29:09

标签: javascript arrays push

在最近的一次采访中,采访者问你可以在javascript中为push()方法编写polyfill。

任何人都知道如何做到这一点。?

2 个答案:

答案 0 :(得分:2)

push()array末尾添加一个或多个元素,并返回数组的新length。您可以使用数组的length属性在其末尾添加元素。

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

答案 1 :(得分:0)

&#13;
&#13;
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;
  };
}
&#13;
&#13;
&#13;