用于JavaScript中push方法的Polyfill [英] Polyfill for push method in JavaScript

查看:53
本文介绍了用于JavaScript中push方法的Polyfill的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

任何人都知道该怎么做。?

any one know how to do this .?

推荐答案

< a href = https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push rel = nofollow> push() array 的末尾添加一个或多个元素,并返回新的 length 数组。您可以使用数组的 length 属性在其末尾添加元素。

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

这篇关于用于JavaScript中push方法的Polyfill的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆