简体   繁体   中英

How to add and remove elements of an Array

I want to maintain a list of things in 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)?

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

I would recommend using push and splice . With push, you don't have to keep track of your last inserted index. Also, with splice, you actually remove the element from the array and you aren't just deleting the reference and making it 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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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