简体   繁体   中英

How to add a element in between array using const array in Javascript

  • How to add an element in array when I am using const array?
    const arr = [2,3,4,5];
    allData = arr[1].concat(9); 
  • Required output: allData = [2,9,3,4,5]

In order to add an item into the middle of an array you can use the .splie() function. You can achieve your desired affect by using the code:

 const arr = [2,3,4,5]; arr.splice(1, 0, 9) console.log(arr)

To understand the use of .splice() . The first param is the starting point, so where we are entering the item into, the second param is how many items will be deleted and finally the last param is what is going to be inserted into the array.

Thanks! Hope this helps!

You can use method SPLICE for arrays. Splice is a powerful method to remove or add at any position an element in an array.

const arr = [2,3,4,5];

ADD AN ELEMENT

add 9 as second element in our array

arr.splice(1, 0, 9)
  • 1 - index where we start, in our case index 1 it's number 3 in our array (because in arrays index 0 it's first element in an array, index 1 it's second element etc...)
  • 0 - how many elements we want to remove, in our case we don't want to remove any, that's why we have 0 here
  • 9 - our element wich we want to add, it can be number, string etc

console.log(array) = [2,9,3,4,5]

REMOVE AN ELEMENT

const arr = [2,3,4,5];

remove the second element(3) and insert 9 instead

arr.splice(1, 1, 9)
  • first argument("1") means that we start at index 1 (so second element in the array).
  • second argument("1") means that we want to remove exactly one element.
  • third argument("9") means that we want to add element 9

console.log(arr) = [2,9,4,5]

I hope this helps you understand the method better.

You can an item in between array using .splice() method.

For further information regarding this you can check this link. [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice][1]

Hope this helps

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