填充工具用于在JavaScript推法(Polyfill for push method in Ja

2019-10-24 01:35发布

在最近的采访中,采访者要求你可以写填充工具push()在JavaScript方法。

有人知道怎么做吗 。?

Answer 1:

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


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



文章来源: Polyfill for push method in JavaScript