前端数组元素上移下移置顶和置底

遇到个表格列上下一定,然后确定保存移动后的位置,这就要用到前端数组移动,然后后端保存移动后的数据
自己写了个上下移动:

function upOrdown(arr, index, type="up") {
	if(type==="up"){
		const current = arr[index];
		const perv = arr[index-1];
		arr[index-1]= current;
		arr[index] = perv;
	}else{
		const current = arr[index];
		const next = arr[index+1];
		arr[index+1]= current;
		arr[index] = next;
	}
	return arr;
}
//例子
var arr = ['ee','rr','tt','yy','ii'];    
//例如 index=2的向前移动
console.log(upOrdown(arr, 2, 'up'));// 打印结果 ["ee", "tt", "rr", "yy", "ii"]
//例如 index=3的向后移动
console.log(upOrdown(arr, 3, ''));// 打印结果 ["ee", "rr", "tt", "ii", "yy"]

巧用splice()第三个入参

/**
 * @description: 
 * @param {*} arr 操作的数组
 * @param {*} index1 准备移动的元素
 * @param {*} index2 移动到的位置  往下移就是 index2=index+1 往上移动就是 index2=index-1;
 * @param {*} direction up->置顶, down->置底
 * @return {*} Array
 */
var swithItem = function (arr, index1, index2, direction) {
	if (direction === 'up') { //置顶
		//arr.unshift(arr[index1]);
		//arr.splice(index1 + 1, 1);
		arr.unshift(arr.splice(index1, 1)[0])
		return arr;
	}
 	if (direction === 'down') { //置底
		//arr.push(arr[index1]);
		//arr.splice(index1, 1);
		arr.push(arr.splice(index1, 1)[0])
		return arr;
	}
	arr[index1] = arr.splice(index2, 1, arr[index1])[0];
	return arr;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值