简体   繁体   English

从数组中删除对象

[英]remove object from an array

I have an array with the following structure : 我有一个具有以下结构的数组:

var y = [{id:12,count:10}, {id:23,count:89}, {id:21,count:100},]

How can I remove element with id:23 ? 如何删除id:23的元素?

I am not willing to use to create a prototype method on the array Array.prototype.remove 我不愿意使用在数组Array.prototype.remove上创建原型方法

Any pointers appreciated 任何指针赞赏

Thanks 谢谢

ES5 code: ES5代码:

y = y.filter(function( obj ) {
    return obj.id !== 23;
});

ES5 is widely supported by all major browsers. 所有主要浏览器均广泛支持ES5。 Still, you might want to include on of the several Shims to backup old'ish browsers 不过,您可能仍要包括几个Shim来备份旧式的浏览器

for (i in y) {
    if (y[i].id == 23) {
       y.splice(i, 1);
       break;
    }
}

Denis Ermolin's answer is an option, though a few problems might occur, here's what I suggest: Denis Ermolin的答案是一个选择,尽管可能会出现一些问题,但我建议这样做:

for(var i=0;i<y.length;i++)
{
    if (y[i].hasOwnProperty('id') && y[i].id === 23)
    {
        delete(y[i]);
        break;
    }
}

When using arrays, it's always better to avoid the for - in loop, as this will loop through the Array.prototype , so i might suddenly contain length , not an index number. 使用数组时,最好避免for - in循环,因为这将遍历Array.prototype ,因此i可能突然包含length而不是索引号。

When you're dealing with objects, the for in loop is a great thing, but again: it loops through the prototypes, that's why you're better off using the hasOwnProperty method. 当您处理对象时, for in循环是一件很了不起的事情,但是再次:它遍历了原型,这就是为什么最好使用hasOwnProperty方法。

The rest is pretty strait forward, I think... good luck 其余的都向前走,我想...祝你好运

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

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