数组的一些小操作

Introduce

入职之后发现有每周答题唉, 一开始紧张的一批,后来发现很有趣唉,哈哈哈哈,我果然没有菜到不可救药

Question

已知数组 arr = [1, 2, 3, 4, 5]

给定索引值,对应数组项向前移动一位
给定索引值,对应数组项移动到最前面
给定索引值,对应数组项移动到最后面
实现任意两个数组项位置互换

Answer

  1. 别人写的,贼简洁,非常棒。

        // 向前一位
        const moveForward = (arr, index) => {
            return exchange(arr, index, index - 1);
        }
        // 最前
        const moveFirst = (arr, index) => {
            arr.unshift(arr.splice(index, 1)[0]);
            return arr;
        }
        // 最后
        const moveLast = (arr, index) => {
            arr.push(arr.splice(index, 1)[0]);
            return arr;
        }
        // 交换
        const exchange = (arr, index1, index2) => {
            arr[index1] = arr.splice(index2, 1, arr[index1])[0];
            return arr;
        }
    
  2. 我写的,想的是通过es6的简单语法的。

    // 已知数组 arr = [1, 2, 3, 4, 5]
        let arr = [1, 2, 3, 4, 5];
        let arrLen = arr.length;
    
        // 抛错
        let throwWrong = (index, leftIndex, rightIndex) => {
          if (index < leftIndex || index > rightIndex) {
            throw new Error('索引越界')
          }
        }
    
        // 无意义
        let undo = (index, compIndex) => {
          if (index === compIndex) {
            console.log("无意义的移动");
          }
        }
    
        // 给定索引值,对应数组项向前移动一位
        let forward = (arr, index) => {
          throwWrong(index, 1, arrLen - 1);
          changePos(arr, index, index - 1);
          return arr;
        }
    
        // 给定索引值,对应数组项移动到最前面
        let goToFirst = (arr, index) => {
          throwWrong(index, 0, arrLen - 1);
          undo(index, 0);
          changePos(arr, 0, index);
          return arr;
        }
    
        // 给定索引值,对应数组项移动到最后面
        let goToLast = (arr, index) => {
          throwWrong(index, 0, arrLen - 1);
          undo(index, arrLen - 1);
          changePos(arr, index, arrLen - 1);
          return arr;
        }
    
        // 实现任意两个数组项位置互换
        let changePos = (arr, onePos, anotherPos) => {
          if (onePos < 0 || anotherPos >= arrLen) {
            throw new Error('索引越界');
          }
          [arr[onePos], arr[anotherPos]] = [arr[anotherPos], arr[onePos]]
          return arr;
        }
    
    

Author

{
  "author""jontyy""email""jontyy@163.com"
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值