【问题标题】:JavaScript Function Overloading UndefinedJavaScript 函数重载未定义
【发布时间】:2018-05-30 14:24:00
【问题描述】:

我有这个用于自定义 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()),它会返回 undefined 并且不会编辑数组。我认为这与函数重载不适用于 0 参数这一事实有关。请你能帮我找到这个问题的替代方案或解决方案。谢谢。

【问题讨论】:

  • 进行某种检查怎么样?
  • Array.remove 确实不存在。
  • @AnwarNairi 我之前在 js 文件中创建了那个方法,没有包含它,抱歉。

标签: javascript function parameters undefined overloading


【解决方案1】:

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

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());

如果您尝试弹出索引无效的值,我还建议您在其中进行一些意义检查以阻止错误。

【讨论】:

  • 我正要建议精确的编辑,更简洁
  • 为了更简洁,可以使用默认参数,直接写Array.prototype.pop = function(index = this.length - 1) { return this.splice(index, 1)[0]; }
  • @MBJH 欢迎。唯一尚未实现该功能的浏览器是 IE(edge 很好),因此如果您担心支持使用较旧 Windows 操作系统(或一般较旧浏览器)的用户,您只想使用默认参数语法如果您通过 babel 之类的预处理器运行代码。
【解决方案2】:

您可能还想使用 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】:

    您甚至不需要检查索引的类型,问题是如果没有提供索引,则 index 不存在并且您试图将实际值传递给非- 存在变量。我要做的是首先改变:

    if (typeof index === "undefined")

    if(!index)

    为了清楚起见。

    然后在 if 块内更改 index = this.length - 1;var index = this.length - 1;

    var 可以解决问题,因为如果使用 var 声明,任何变量都可以在该范围之外访问。

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 2013-06-26
      • 2011-05-21
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 2022-01-10
      相关资源
      最近更新 更多