数组两个元素互换位置

参考:
上移、下移、置顶:https://blog.csdn.net/Chou_Junn/article/details/84967408

JavaScript 交换数组元素位置的几种方式:https://www.cnblogs.com/shapeY/p/9669924.html

数组元素互换方法:

第三方变量
  let temp = array[index1];
  array[index1] = array[index2];
  array[index2] = temp;
不使用变量,加减法(也可以用乘除法)
public static void swap(int[] a, int i, int j){
    a[i] = a[i] + a[j];
    a[j] = a[i] - a[j]; // a[j] = a[i] + a[j] - a[j]
    a[i] = a[i] - a[j]; // a[i] = a[i] + a[j] - a[i]
}

splice
function swapArr(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
}
解构赋值
[array[index1],array[index2]] = [array[index2],array[index1]];
代码中使用的方法

/**
 * 增加case\then
 */
addCase() {
  this.expressionList.push({case: "", then: ""});
}
/**
 * 删除case\then
 */
delete(index) {
  if (this.expressionList.length == 1) return;
  this.expressionList.splice(index, 1);
}
/**
 * 上移case\then
 */
up(index) {
  if (index == 0) return;
  this.swopItems(this.expressionList, index, index - 1)
}
/**
 * 下移case\then
 */
down(index) {
  if (index == this.expressionList.length - 1) return;
  this.swopItems(this.expressionList, index, index + 1)
}
/**
 * 交换数组元素
 */
swopItems(arr, index1, index2) {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
  return arr;
};
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值