简体   繁体   中英

Javascript - How to insert an element from a specific index to the end of the array?

Each of the element in my list has an Array to hold comments, such as

for (let i = 0; i < myList; i ++) {
    myList[i][‘comments’] = [];
}

My failed attempt:

if (someCondition) {
    // insert from index k to the end of the array
    myList[‘comments’].splice(k, 0, “newElement”);
} 

An example:

myList = [ “comments”: [“1, 2”], “comments”:[], “comment”: [“2”, “2”], “comment”: [] ] 

Goal: Insert from index 2

myList = [ “comments”: [“1, 2”], “comments”:[], “comment”: [“2”, “2”, “newElement"], “comment”: [“newElement”] ]

array.push("string"); will push an element to the end of the array.

array.splice(k,1); will delete the item with key=k from the array.

You could do something like:

array.push(array[k]);
array.splice(k,1);

To add an element to your array you can use the spread operator.

let myArray = [ 1, 2, 3, 4];
myArray = [ ...myArray, 5 ]; // This will add 5 to your array in the very last

Or if you prefer to add it in the first position in your array you can simply do something like this.

myArray = [ 55, ...myArray]; // Will add 55 as the first index in your array

To remove an element from the array you can use Array.filter method. Which is as follows;

myArray = myArray.filter(val => val !== 5); // This will remove 5 element from your array.

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