代码之家  ›  专栏  ›  技术社区  ›  MBJH

未定义的javascript函数重载

  •  0
  • MBJH  · 技术社区  · 7 年前

    我有一个自定义pop()方法的代码:

    Array.prototype.pop = function(index) {
        if (typeof index === "undefined") {
            index = this.length - 1;
        }
        var rtn = this.slice()[index];
        this.remove(this[index]);
        return rtn;
    };
    

    当我输入参数(例如 [1,3,5].pop(1) 返回3并删除它)。
    但是,当我在没有参数的情况下使用它时(例如 [1,3,5].pop() )它返回未定义且不编辑数组。我认为这是因为函数重载不适用于0参数。你能帮我找到解决这个问题的办法吗?谢谢。

    3 回复  |  直到 7 年前
        1
  •  2
  •   Reinstate Monica Cellio    7 年前

    如果你想要我认为你想要的(返回索引值并删除它,或者如果没有索引使用最后一个值),那么这就是你想要的…

    Array.prototype.pop = function(index) {
        if (typeof index === "undefined") {
            index = this.length - 1;
        }
        // remove an array starting at index, with a length of 1,
        // and return the first value
        return this.splice(index, 1)[0];
    };
    
    // pop value by index
    var arr = [1, 3, 5];
    
    console.log(arr.pop(1));
    console.log(arr.toString());
    
    // pop last value
    var arr = [1, 3, 5];
    
    console.log(arr.pop());
    console.log(arr.toString());

    我还建议在其中进行一些有意义的检查,以便在尝试弹出一个索引无效的值时停止错误。

        2
  •  0
  •   Anwar    7 年前

    您可能还希望使用foreach循环并创建一个新数组来填充元素,前提是键不是参数中提供的键。

    还要注意,您可以使用一些默认值简化第一次检查。看一看( view online ):

    Array.prototype.pop = function(key = this.length - 1) {
        let array = [];
    
        this.forEach(function(element, index) {
          if( index !== key ) {
            array.push(element);
          }
        });
    
        return array;
    };
    
    console.log([1,3,5].pop(1)); // [1, 5]
    console.log([1,3,5].pop()); // [1, 3]
    

    不用说 强烈建议重写现有原型 ,你应该想到另一个花哨的名字,比如 Array.prototype.eject

        3
  •  0
  •   Bargros    7 年前

    您甚至不需要检查索引的类型,问题是如果没有提供索引,那么 指数 不存在,您正在尝试将实际值传递给不存在的变量。我要做的是第一个改变:

    if (typeof index === "undefined")

    对于

    if(!index)

    然后在 如果 块更改 index = this.length - 1; 对于 var index = this.length - 1;

    var 技巧是什么,因为如果用 var .

    推荐文章