随机生成 指定位数的字符串,数字,随机日期时间,随机boolean,随机select选中项

根据传入的类型type,传入的随机select选项,

随机生成不重复的字符串,随机数字(可重复),随机时间日期,随机boolean值, select随机选中项

数字类型 ‘INTEGER’ ‘LONG’ ‘DOUBLE’ ‘Currency’

字符串类型 ‘STRING’

日期时间类型 ‘DATE’ 'TIMESTAMP


createRandomString (type = 'STRING', dictValues = []) { // 随机生成符合类型的数据
    let str = ''
    let long = Math.round(Math.random() * 6 + 2) //  6-8位
    let words = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    let len = words.length
    let start = 0
    let end = len
    if (type === 'INTEGER' || type === 'LONG' || type === 'DOUBLE' || type === 'Currency' || type === 'STRING') {

      if (type !== 'STRING') {
        end = 9
        len = 10
      }
      for (let i = 0; i < long; i++) {
        let newWord = words.substring(start, end).charAt(Math.floor(Math.random() * len))
        if (!newWord || (type === 'STRING' && str.indexOf(newWord) > -1) || (i === 0 && newWord * 1 === 0)) {
          i--
          continue
        }
        str += newWord
      }
    } else if (type === 'DATE' || type === 'TIMESTAMP') {
      let startTime = +new Date('1990-01-01T00:00:00')
      let nowTime = +new Date()
      let long = nowTime - startTime
      // str = moment(startTime + Math.round(Math.random() * long)).format('YYYY-MM-DD HH:mm:ss')
      str = startTime + Math.round(Math.random() * long)
    } else if (type === 'Boolean') {
      str = ['true', 'false'][Math.round(Math.random() * 1)]
    } else if (type === 'DICTIONARY' && dictValues.length > 0) {
      let index = Math.floor(Math.random() * dictValues.length)
      str = dictValues[index].dictValue || ''
    }
    return str
  }


猜你喜欢

转载自blog.csdn.net/u010762099/article/details/89455872
今日推荐