用于JavaScript的推送方法的Polyfill

问题描述 投票:1回答:2

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

有人知道怎么做吗 。?

javascript arrays push
2个回答
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;
    };
}

0
投票

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;
  };
}
© www.soinside.com 2019 - 2024. All rights reserved.