
6

JS使用Splice()函数操作数组
source link: http://www.z16388.top/2019/11/16/jssplice/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JS使用Splice()函数操作数组
2019-11-16
9
在js的使用过程中,有一次需要对数组进行各种操作,一时间迫使我想要去使用链表。后来通过查阅资料,总结了下面的一些方法,主要使用了splice()函数。
下面的方法主要是使用下标进行操作。如果是用值的话,可以通过indexOf()
函数来获取下标。若不存在则返回-1。
function swap_arr(a_list, index1, index2) {
a_list[index1] = a_list.splice(index2, 1, a_list[index1])[0];
return a_list;
function up_arr(a_list, index){
if(index!=0 && index!=-1){
a_list[index] = a_list.splice(index-1, 1, a_list[index])[0];
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];
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;
在顶部插入
function topins_arr(a_list, a_data) {
a_list.splice(0, 0, a_data)
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);
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK