打乱 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 (chj@8cuo.net)
 * @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'

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值