javascript - 我的删除功能有什么问题?

标签 javascript

Array.prototype.remove = function (obj) {
    for(var i = 0; i < this.length; i++) {
        if(this[i] === obj) {
            if (i == this.length) {
                this[i] = null;
            } else {
                for(var j = i; j < this.length-1; j++) {
                    this[j] = this[j+1];
                }
                delete this[j]; // updated from this[j] = null; still not working.
            }
        }
    }
    return this;
};

调用它:

write("ARRAY TEST = " + [22, 33, 44].remove(33).remove(22));

..它打印:

44,,

为什么这 2 个逗号以及如何修复我的删除功能以删除逗号?

最佳答案

delete Array 不会删除元素,它会将其设置为 undefined。由于 undefined 打印结果为空字符串,这解释了 write() 的结果。

您需要使用 splice()删除元素。如果将它与 indexOf 结合使用(你可能需要为旧浏览器定义它)你得到一个非常短的函数:

Array.prototype.remove = function (obj) {
    this.splice(this.indexOf(obj), 1);
    return this;
}

PS:我不提倡扩展原生原型(prototype)......

关于javascript - 我的删除功能有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4878893/

相关文章:

javascript - 在 amcharts4 的气泡图中的气泡下标记

javascript - 类型错误 : 'undefined' is not a function (evaluating '$( "#wnd_Addparam"). 对话框')

javascript - NodeJS : Write a js object to file and do exports

javascript - 无法禁用文本区域中的逗号

javascript - 如何使用带有 Angular js 和 Bootstrap 的 "Cancel"按钮关闭模态

javascript - 想要在 Angular JS 中将多个 json 对象转换为数组

javascript - 如何创建具有特定渐变分布的 HTML 颜色数组?

javascript - 元素不可见但仍然是 DOM 的一部分以进行操作?

javascript - SharePoint JavaScript 执行一个又一个异步函数

javascript - 如何在 Flow 中用多个可能的调用签名来注释一个函数?