在js的使用过程中,有一次需要对数组进行各种操作,一时间迫使我想要去使用链表。后来通过查阅资料,总结了下面的一些方法,主要使用了splice()函数。

下面的方法主要是使用下标进行操作。如果是用值的话,可以通过indexOf()函数来获取下标。若不存在则返回-1。

值交换

1
2
3
4
function swap_arr(a_list, index1, index2) {
a_list[index1] = a_list.splice(index2, 1, a_list[index1])[0];
return a_list;
}

置顶

1
2
3
4
5
function up_arr(a_list, index){
    if(index!=0 && index!=-1){
a_list[index] = a_list.splice(index-1, 1, a_list[index])[0];
    }
}

下移

1
2
3
4
5
function down_arr(a_list, index) {
    if(index!=a_list.length-1 && index!=-1){
a_list[index] = a_list.splice(index+1, 1, a_list[index])[0];
    }
}

插入

1
2
3
4
5
6
7
8
9
10
11
function ins_arr(a_list, index, a_data) {
if(index!=-1){
if (a_list.indexOf(a_data)==-1) {
a_list.splice(index+1, 0, a_data);
return true;
}
else {
return false;
}
}
}

在顶部插入

1
2
3
function topins_arr(a_list, a_data) {
a_list.splice(0, 0, a_data)
}

删除元素

1
2
3
4
5
6
7
8
function del_arr(a_list, a_data_list) {
for (const ele of a_data_list) {
let index = a_list.indexOf(ele);
if(index!=-1){
a_list.splice(index, 1);
}
}
}