Javascript 如何推送到特定位置的数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8754508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:22:38  来源:igfitidea点击:

How to push to an array in a particular position?

javascriptarrayscoffeescript

提问by fancy

I'm trying to efficiently write a statement that pushes to position 1 of an array, and pushes whatever is in that position, or after it back a spot.

我正在尝试有效地编写一个语句,该语句将推入数组的位置 1,并将该位置中的任何内容推入,或将其推回一个位置。

array = [4,5,9,6,2,5]

#push 0 to position 1

array = [4,0,5,9,6,2,5]

#push 123 to position 1

array = [4,123,0,5,9,6,2,5]

What is the best way to write this? (javascript or coffeescript acceptable)

写这个的最好方法是什么?(可以接受javascript或coffeescript)

Thanks!

谢谢!

回答by fancy

array = [4,5,9,6,2,5]

#push 0 to position 1
array.splice(1,0,0)

array = [4,0,5,9,6,2,5]

#push 123 to position 1
array.splice(1,0,123)

array = [4,123,0,5,9,6,2,5]

回答by Vlada

To push any item at specific index in array use following syntax

要推送数组中特定索引处的任何项目,请使用以下语法

// The original array
var array = ["one", "two", "four"];
// splice(position, numberOfItemsToRemove, item)
array.splice(2, 0, "three");

console.log(array);  // ["one", "two", "three", "four"]

回答by Vlada

The splice()function is the only native array function that lets you add elements to the specific place of an array

splice()函数是唯一的原生数组函数,可让您将元素添加到数组的特定位置

I will get a one array that you entered in your question to describe

我会得到一个你在问题中输入的数组来描述

splice(position, numberOfItemsToRemove, item)
  • position= What is the position that you want to add new item
  • numberOfItemsToRemove= This indicate how many number of items will deleted. That's mean delete will start according to the position that new item add.
  • position=您要添加新项目的位置是什么
  • numberOfItemsToRemove= 这表示将删除多少个项目。这意味着删除将根据新项目添加的位置开始。

Ex= if you want to add 1 position to 123 result will be like this ([4,123,0,5,9,6,2,5]) but if you give numberOfItemsToRemoveto 1 it will remove first element after the 123 if you give 2 then its delete two element after 123.

例如= 如果你想在 123 上添加 1 个位置,结果将是这样的 ([4,123,0,5,9,6,2,5]) 但如果你给numberOfItemsToRemove1,它将删除 123 之后的第一个元素,如果你给2 然后它删除 123 之后的两个元素。

  • item= the new item that you add
  • item= 您添加的新项目

function my_func(){
        var suits = [4,0,5,9,6,2,5]
        
        suits.splice(1 , 0 , 123);

        document.getElementById('demo').innerHTML = suits;
}
<button id="btn01" onclick="my_func()">Check</button>
<p id="demo"></p>