我有一个自定义 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/