简体   繁体   English

如何在 Javascript 中使用 const 数组在数组之间添加元素

[英]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 数组时如何在数组中添加元素?
    const arr = [2,3,4,5];
    allData = arr[1].concat(9); 
  • Required output: allData = [2,9,3,4,5]所需输出:allData = [2,9,3,4,5]

In order to add an item into the middle of an array you can use the .splie() function.为了将项目添加到数组的中间,您可以使用.splie()函数。 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() .了解.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 Splice is a powerful method to remove or add at any position an element in an array. Splice 是一种强大的方法,可以在数组中的任何位置删除或添加元素。

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

ADD AN ELEMENT添加元素

add 9 as second element in our array在我们的数组中添加 9 作为第二个元素

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...) 1 - 我们开始的索引,在我们的例子中,索引 1 是我们数组中的第 3 号(因为在数组中,索引 0 是数组中的第一个元素,索引 1 是第二个元素等...)
  • 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 0 - 我们要删除多少元素,在我们的例子中我们不想删除任何元素,这就是我们在这里有 0 的原因
  • 9 - our element wich we want to add, it can be number, string etc 9 - 我们要添加的元素,可以是数字、字符串等

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删除第二个元素(3)并插入 9 代替

arr.splice(1, 1, 9)
  • first argument("1") means that we start at index 1 (so second element in the array).第一个参数(“1”)意味着我们从索引 1 开始(所以数组中的第二个元素)。
  • second argument("1") means that we want to remove exactly one element.第二个参数(“1”)意味着我们要删除一个元素。
  • third argument("9") means that we want to add element 9第三个参数(“9”)表示我们要添加元素 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.您可以使用 .splice() 方法在数组之间添加一个项目。

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] [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice][1]

Hope this helps希望这可以帮助

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

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