JavaScript 函数重载未定义

标签 javascript function parameters undefined overloading

我有一个自定义 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 个参数。请你帮我找到这个问题的替代方案或解决方案。谢谢。

最佳答案

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

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

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

关于JavaScript 函数重载未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50607162/

相关文章:

php - 这个功能有什么问题?

c - 如何修改已传递给 C 函数的指针?

java - 如何仅使用构造函数的部分参数? ( java )

javascript - jQuery:限制减少时帮助重新激活按钮

javascript - `React.createClass({})()`何时被调用

javascript - Fabric JS : Set X Y Coordinates in Canvas Image | Set Position in Canvas Image

javascript - React 在 return 中调用函数来插入组件

php - 在执行函数之前检查sql中的日期时间

ruby - 有没有办法在ruby中返回方法参数名称

javascript - Flask - 我想要一种基于数据库数据显示任务流程图的方法