首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript中push方法的Polyfill

JavaScript中push方法的Polyfill
EN

Stack Overflow用户
提问于 2015-07-21 16:29:09
回答 2查看 1.4K关注 0票数 1

在最近的采访中,面试官问道,你能用javascript为push()方法编写polyfill吗?

任何人都知道该怎么做。

EN

回答 2

Stack Overflow用户

发布于 2015-07-21 16:30:18

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

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2018-03-03 15:04:44

代码语言:javascript
复制
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;
  };
}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31533963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档