关于javascript:如何将一个新项目“推”到数组的中间?

How to "push' a new item to the middle of an array?

本问题已经有最佳答案,请猛点这里访问。

我刚刚完成了第1节,注意到在如何将一个项推送到数组的特定位置上,还没有介绍任何方法。例如,如果我想让数组显示

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

我怎样才能将"布鲁克斯兄弟"推进到列阵服的位置[2]并将其余的1向下移动?是否有类似于push的javascript内置函数可以让我做到这一点?

我想我总可以,尽管有些困难:

1
2
3
4
5
6
7
8
9
10
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


您可以使用Array.splice在特定位置将项插入到数组中。

1
2
3
4
5
const suits = ["hearts","clubs","Brooks Brothers","diamonds","spades"];

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

console.log(suits);


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

方法通过删除现有元素和/或添加新元素来更改数组的内容。

1-插入单个值

1
2
3
4
5
6
7
8
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);

2-将阵列插入西服阵列

1
2
3
4
5
6
7
8
9
10
11
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);


您应该使用拼接功能

arr.splice(index, 0, item);将在指定的索引处将项目插入arr(首先删除0个项目,也就是说,它只是一个插入)。

1
2
3
4
5
var suits = ["hearts","clubs","Brooks Brothers","diamonds","spades"]

suits.splice(2, 0,"somevalue");

console.log(suits);


在javascript中没有用于此的内置函数,但您可以使用拼接来完成此操作。

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

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

这将把x项插入到数组suits的索引2中,["hearts","clubs","Brooks Brothers","Brooks Brothers","diamonds","spades"]

句法

1
.splice(<position-to-insert-items>,0,<item-1>,<item-2>,..,<item-n>)

Always pass second second argument as 0, because we don't want to delete
any item from the array while splicing.