打乱 json 数组内的数据顺序

场景:较适合后台返回的是所有数据 前端自己做分页功能 如果分页功能是后台做的 那么乱序就要考虑分页了

原理:

循环遍历该数组,在每次遍历中产生一个0 ~ length - 1的数,该数代表本次循环要随机交换的位置。
将本次循环当前位置的数随机位置的数进行交换。

json数据格式:

代码:

// 乱序
// this.selectedData 是接口返回的json数据
    upsetOrder () {
      let arr = deepCopy(this.selectedData)
      for (let i = 0, len = arr.length; i < len; i++) {
        let random = parseInt(Math.random() * (len - 1));
        let current = arr[i];
        arr[i] = arr[random];
        arr[random] = current;
      }
      // 乱序后 重置权重
      let number = 0
      arr.forEach((e, i) => {
        e.weight = number += 2
      })
      this.selectedData = arr
    },

补充deepCopy:为了避免数据(this.selectedData)被好几处直接赋值容易出现问题的情况 使用deepCopy 拷贝一下 避免内存泄漏。(如果嫌麻烦 也可以直接赋值 不使用deepCopy)

deepcopy.js:

/**
 * @file    deepcopy
 * @authors KevinChan ([email protected])
 * @date    2019/4/15 下午6:57:42
 */
function deepCopy (obj, cache = []) {
  function find (list, f) {
    return list.filter(f)[0]
  }
  // just return if obj is immutable value
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  // if obj is hit, it is in circular structure
  const hit = find(cache, c => c.original === obj)
  if (hit) {
    return hit.copy
  }

  const copy = Array.isArray(obj) ? [] : {}
  // put the copy into cache at first
  // because we want to refer it in recursive deepCopy
  cache.push({
    original: obj,
    copy
  })

  Object.keys(obj).forEach(key => {
    copy[key] = deepCopy(obj[key], cache)
  })

  return copy
}

export default deepCopy;

使用:

在需要使用deepCopy的页面直接引入即可

import deepCopy from '@/utils/deepcopy'

猜你喜欢

转载自blog.csdn.net/weixin_50114203/article/details/127882446