简体   繁体   English

如何添加和删除数组的元素

[英]How to add and remove elements of an Array

I want to maintain a list of things in javascript. 我想维护一个javascript列表。 This seems to be a non trivial problem in this language... 用这种语言这似乎不是一个小问题。

var things = []

// for adding:
things[things.length] = thing

// for removing:
delete (things[things.indexOf(thing)])

This kinda works, but I fear the adding is a bug. 这有点用,但我担心添加的是错误。 When a thing that is not at the end of the array gets removed, a following add operation will overwrite an existing element, right? 当删除不在数组末尾的内容时,以下添加操作将覆盖现有元素,对吗? Because length is the number of elements. 因为长度是元素的数量。

How to do the adding correctly? 如何正确添加? Or is there a better way to do this with plain javascript (no JQuery)? 还是有使用纯JavaScript(没有JQuery)做到这一点的更好方法?

对于添加,您想使用push ,所以Things.push(yourThing);

I would recommend using push and splice . 我建议使用pushsplice With push, you don't have to keep track of your last inserted index. 使用push,您不必跟踪最后插入的索引。 Also, with splice, you actually remove the element from the array and you aren't just deleting the reference and making it null. 另外,使用拼接实际上是从数组中删除该元素,而不仅仅是删除引用并将其设置为null。

Something like this would work: 这样的事情会起作用:

things.push(thing);
things.splice(index, 1);

I would use a loop. 我会使用一个循环。

var index;
var things= [];
for (index = 0; index < things.length; ++index) {
    text += things[index];
}

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

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