前端常见数据处理

作为一个前端开发,经常会有处理接口返回数据的需求,这里举例了一些本人在工作中遇到的一些数据处理,用作记录。

因项目不同,以下方法有涉及vue、react、微信小程序等,大同小异,各位如有需要自行转化就好了。

记得点赞评论收藏哦,ღ( ´・ᴗ・` )比心

数量传换 转万和亿

export const simplifyAlbumPlayCount = (number: number | string) => {
  const num = parseInt(number as string, 10),
    divided_wan = Math.pow(10, 4),
    divided_yi = Math.pow(10, 8)

  if (num < divided_wan) {
    return num
  } else if (num >= divided_wan && num < divided_yi) {
    return `${(num / divided_wan).toFixed(1)}万`
  } else {
    return `${(num / divided_yi).toFixed(1)}亿`
  }
}

时间转化

export const timeToString = time => {
  time = ~~time
  let min, second
  if (time < 10) {
    min = `00`
    second = `0${time}`
  } else if (time >= 10 && time < 60) {
    min = `00`
    second = time
  } else if (time >= 60 && time) {
    const sec = time % 60
    min = Math.floor(time / 60)
    min = min > 9 ? min : `0${min}`
    second = sec > 9 ? sec : `0${sec}`
  }
  return `${min}:${second}`
}

时间戳转换今天、昨天、前天

export const timeToTYBY = timestamp => {
  const tTime = new Date(new Date().toLocaleDateString()).getTime()
  const eTime = 24 * 60 * 60 * 1000 //一天时间(long)
  const yTime = tTime - eTime //昨天凌晨时间(long)
  const byTime = tTime - 2 * eTime //前天凌晨时间(long)
  if (timestamp >= tTime) {
    return '今天'
  } else if (timestamp < tTime && timestamp >= yTime) {
    //昨天
    return '昨天'
  } else if (timestamp < yTime && timestamp >= byTime) {
    //前天
    return '前天'
  } else {
    return ''
  }
}

url请求参数

export const getQueryObj = url => {
  url = decodeURIComponent(url)
  const query = ~url.indexOf('?') ? url.split('?')[1] : url
  const params = query.split('&')
  const paramsObj = {}
  for (let i = 0, len = params.length; i < len; i++) {
    let item = params[i].split('=')
    paramsObj[item[0]] = item[1]
  }
  return paramsObj
}

时间戳转化日月

export const timeToMd = timestamp => {
  const date = new Date(timestamp)
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

根据身份证号联动性别年龄

    let idCard = e.detail.value
    let birthday = ''
    let age = ''
    let sex = ''
    if (idCard.length < 14) {
      birthday = ''
      age = ''
      return
    }
    birthday = idCard.slice(6, 10) + '-' + idCard.slice(10, 12)+ '-' + idCard.slice(12, 14)
    let d = new Date()
    let birthdays = new Date(idCard.slice(6, 10) + '-' + idCard.slice(10, 12) + '-' + idCard.slice(12, 14))
    age = d.getFullYear() - birthdays.getFullYear() - (d.getMonth() < birthdays.getMonth() || (d.getMonth() == birthdays.getMonth() && d.getDate() < birthdays.getDate()) ? 1 : 0)
    if (parseInt(idCard.substr(16, 1)) % 2 == 1) {
      sex = '男'
    } else {
        //女
      sex = '女'
    }
    this.setData({
      idCard: idCard,
      date: birthday,
      age: age,
      sex: sex
    })
    ```

你可能感兴趣的:(工具,前端,javascript,vue.js)