如何将新项目“推”到数组的中间?

1 javascript

我刚刚完成了section1,并注意到没有介绍如何将项目推到数组的特定位置的方法。例如,如果我想显示数组

var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"]
Run Code Online (Sandbox Code Playgroud)

如何将“ Brooks Brothers”推入阵列服的位置[2],并将其余的1向下移?javascript中是否有类似于push的内置函数,使我能够做到这一点?

我想我总是可以有些困难:

function add (item, position){
    var length = suits.length;
    for(i = length -1; i >= position; i--){
        suits[length] = suits[i];
        length--;
    };
    suits[position] = item;
};

add("Brooks Brothers",2) //to add it to the middle
Run Code Online (Sandbox Code Playgroud)

Cod*_*eIt 15

JavaScript 中没有为此内置函数,但您可以使用splice简单地做到这一点

var suits = ["hearts", "clubs", "Brooks Brothers", "diamonds", "spades"];

suits.splice(2, 0, "Brooks Brothers");

console.log(suits);
Run Code Online (Sandbox Code Playgroud)

这会将项目 X 插入数组套装的索引 2, ["hearts", "clubs", "Brooks Brothers", "Brooks Brothers", "diamonds", "spades"]

句法

<array-name>.splice(<position-to-insert-items>,0,<item-1>,<item-2>,..,<item-n>)
Run Code Online (Sandbox Code Playgroud)

始终将第二个第二个参数传递为 0,因为我们不想在拼接时从数组中删除任何项目。


fel*_*osh 5

您可以使用Array.splice,以便在特定的地方插入项目阵列。

const suits = ["hearts", "clubs", "Brooks Brothers", "diamonds", "spades"];

suits.splice(2, 0, 'newItem');

console.log(suits);
Run Code Online (Sandbox Code Playgroud)


Hey*_*eep 5

您可以使用内置的拼接功能

拼接()方法通过去除现有元件和/或添加新元素改变的数组的内容。

1- 插入单个值

var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"];

//1st param is insert index = 2 means insert at index 2
//2nd param is delete item count = 0 means delete 0 elements
//3rd param is new item that you want to insert
suits.splice(2, 0 , "Test");

console.log(suits);
Run Code Online (Sandbox Code Playgroud)

2- 将数组插入您的西装数组

var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"];

var newSuitsToInsert = ["test1", "test2","hello"];

    //1st param is insert index = 2 means insert at index 2
    //2nd param is delete item count = 0 means delete 0 elements
    //3rd param is new item that you want to insert
    //... is the spread syntax which will expand elements as one
    suits.splice(2, 0 , ...newSuitsToInsert);

    console.log(suits);
Run Code Online (Sandbox Code Playgroud)