繁体   English   中英

从数组中删除对象?

[英]Remove an object from an array?

我有这个应用程序,可以让用户选择他的颜色首选项,并在以后决定更改它们时进行更改。 该应用程序无需在页面重新加载之间工作。 我希望用户能够从下拉列表中删除特定的颜色首选项。 我想使用indexOf和splice,但是我一直在努力使用它。 这是我到目前为止的工作。 问题出在Remove()中。 JS Bin: http//jsbin.com/ANENaRid/2/

这是故障功能:

function Remove() {
    var select = document.getElementById("selectColor");
    for (var i = 0; i < colors.length; i--) {
        var selectIndex = colors.indexOf(select.value);
        if (selectIndex !== -1) {
            colors.splice(i, 1);
        }
        return false;
    }
}

remove函数应该看起来像这样,您也必须从select中删除该选项(仅构造函数名称应为大写):

function remove() {
    var select = document.getElementById("selectColor");
    for (var i = 0; i < colors.length; i++) {
        if (colors[i].name_prop == select.value) {
            colors.splice(i, 1);
        }
     }
}
function Remove() {
    var select = document.getElementById("selectColor");
    var selectIndex = colors.indexOf(select.value);
    if (selectIndex !== -1) {
        colors.splice(selectIndex , 1);
    }
    return false;
}

而不是遍历颜色数组,您应该只选择要删除的颜色。 您获得该项目的索引并将其删除。 无需迭代。

使用之一

for(var i = 0; i < colors.length; i++) { 
    //your code here
}

要么

for(var i = colors.length-1; i >= 0; i--) { 
    //your code here
}

在你的循环

并将return语句放入if块的内部

您可以改为调用表单重置功能。

删除示例元素的样式属性!

这可能会有所帮助:

for (var i = 0; i < colors.length; i++) {
    var index = colors[i].name_prop.indexOf(select.value);
    if (index !== -1) {
        colors.splice(i, 1);
        return false;
    }
}

indexOf可能是无用且不可靠的。 但我懒得进一步调查,请以其他方式查看此答案: https : //stackoverflow.com/a/20900571/1636522

我重构了您的删除功能;

function Remove () {
    var selectedIndex = document.getElementById("selectColor").selectedIndex;
  var options=document.getElementById("selectColor").options;
    for(var i = 0; i < options.length; i++) {
            if(options[selectedIndex].text === colors[i].name_prop){
              alert(colors[i].name_prop + "removed");
            colors.splice(i, 1);
               return false;
        }

     }
}

它从颜色数组中删除选定的项目

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM