我有一个对象数组
var Country = [];
它就像

{
    "Name" : "IND"
    "Capital" : "Delhi"
    id : someID1
},
{
    "Name" : "USA"
    "Capital" : "WS"
    id : someID2
},
{
    "Name" : "UK"
    "Capital" : "London"
    id : someID3
}

现在我想在某些条件下删除元素。但它抛出了超过 2 条记录的错误。

我的错误是:
无法读取未定义的 的属性“id”

我的代码是
remove : function(me, record, index){
    var CountryRec = this.Country;
    var CountryLen = this.Country.length;
    for(var i=0; i<CountryLen; i++){
        if(record.data.id == this.CountryRec[i].id){
            //delete this.checkRec[i];
            checkRec.splice(i,1);
        }
    }
}

这引发了超过 2 条记录的错误。请告诉我我做错了什么。

最佳答案

假设你有唯一的id,那么你可以在与 break 拼接后离开循环

var CountryRec = this.Country;
var CountryLen = this.Country.length;
for (var i = 0; i < CountryLen; i++) {
    if(record.data.id == CountryRec[i].id) {
        CountryRec.splice(i, 1);
        break;
    }
}

关于javascript - 从数组中删除元素时 id 未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46149893/

10-11 02:49
查看更多