网络编程
位置:首页>> 网络编程>> JavaScript>> 基于js实现数组相邻元素上移下移

基于js实现数组相邻元素上移下移

作者:苏小落  发布时间:2024-07-11 01:01:34 

标签:js,数组,元素

实现效果:

基于js实现数组相邻元素上移下移

即需要实现当前元素与相邻元素交换位置,

当上移时,则是当前元素与上一元素调换位置;当下移时,则是当前元素与下一元素调换位置。

实现代码:

js:


//点击上移
clickUp(index){
this.swapArray(this.tableData, index-1, index);
},
//点击下移
clickDown(index){
this.swapArray(this.tableData, index, index+1);
},
//数组元素互换位置
swapArray(arr, index1, index2) {
arr[index1] = arr.splice(index2, 1, arr[index1])[0];
return arr;
},

html:


<el-table-column label="顺序调整" min-width="80" align="center">
<template slot-scope="scope">
 <div class="img_style">
  <img src="@/assets/images/up_01.png" v-if="scope.$index == 0">
  <img src="@/assets/images/up.png" @click="clickUp(scope.$index)" v-else>
  <img src="@/assets/images/down_01.png" v-if="scope.$index == tableData.length - 1">
  <img src="@/assets/images/down.png" @click="clickDown(scope.$index)" v-else>
 </div>
</template>
</el-table-column>

注意:

1.思想就是在数组中交换两个元素的位置,使用splice()的替换;

2.上移是跟上一元素交换位置,下移是跟下一元素交换位置,不同体现在调用调换方法时传入的index参数不同。

来源:https://www.cnblogs.com/5201314m/p/12901755.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com