zhangxinxu/quiz

你这个正则判断下标是否合法不对啊,数组长度超过9的时候,你这就没法玩了

Closed this issue · 1 comments

1. 交换位置
function exchangeArr (arr, index1, index2) {
  let reg = new RegExp(`^[0-${arr.length}]$`)
  // 校验索引
  if (!reg.test(index1) || !reg.test(index2)) {
    return new Error('索引有误!!!')
  }
  [arr[index1], arr[index2]] = [arr[index2], arr[index1]]
  
  return arr
}
2. 位置前移
  function toForward (arr, index) {
    return exchangeArr(arr, index, index - 1)
  }
3. 位置移动最前
  function toFirstPosition (arr, index) {
    let reg = new RegExp(`^[0-${arr.length}]$`)
    // 校验索引
    if (!reg.test(index)) {
      return new Error('索引有误!!!')
    }
     arr.unshift(arr[index])
     arr.splice(index + 1, 1)
     return arr
  }
4. 位置移动最后
  function tolastPosition (arr, index) {
    let reg = new RegExp(`^[0-${arr.length}]$`)
    // 校验索引
    if (!reg.test(index)) {
      return new Error('索引有误!!!')
    }
    arr.push(arr[index])
    arr.splice(index, 1)
    return arr
  }
let arr = [0,1,2,3,4,5]
console.log(exchangeArr(arr,3,5))

Originally posted by @asyncguo in #8 (comment)

cool,感谢提醒,已修复!