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

版权声明:本文为博主前端基础文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

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

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

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

字符串类型 ‘STRING’

日期时间类型 ‘DATE’ ‘TIMESTAMP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
}