使用js实现数组上移和下移,交换位置以及将目标元素移动到指定位置, 其余元素不变

// 上移下移

dropdown = (i) => { // 下移事件
    const res = this.handleMove(1, i, this.arr)
},
   
dropup = (i) => { // 上移事件
    const res = this.handleMove(0, i, this.arr)
}

handleMove = (status, index, arr) => {
    // status: 0-表示上移|1-表示下移;index表示当前下标; arr数组
    const data = JSON.parse(JSON.stringify(arr)); // 数组属于引入类型
    if (status == 0) {
        if (index != 0) {
            // 上移第一项无需上移
            data.splice(index - 1, 2, arr[index], arr[index - 1]);
        } else {
            console.log('已经是首项了');
        }
    } else if (status == 1) {
        // 下移最后一项无需下移
        if (index != arr.length) {
            data.splice(index, 2, arr[index + 1], arr[index]);
        } else {
            console.log('已经是最后一项了');
        }
    }
    return data;
};

// 交换位置以及将目标元素移动到指定位置, 其余元素不变

/**
 * 数组元素交换位置
 * @param {array} arr 数组
 * @param {number} index1 添加项目的位置(当前数组点击的索引)
 * @param {number} index2 删除项目的位置(要移动到数组具体位置的索引)
 */
handleSwapArray = (arr, index1, index2) => {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
};



/**
 * 将目标元素移动到指定位置, 其余元素不变
 * @param {array} arr 数组
 * @param {number} curIndex 添加项目的位置(当前数组点击的索引)
 * @param {number} tarIndex 移动到指定位置(要移动到数组具体位置的索引)
 */
const tQCategoryManagerList = [1, 2, 3];
const curList = tQCategoryManagerList.splice(curIndex, 1);
tQCategoryManagerList.splice(tarIndex, 0, curList[0]);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值