关于生成随机id
同志们对于生成随机id有啥好的方法吗?
网上应该也有不少包,之前自己写过一个js版的
const getGuid = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = (Math.random() * 16) | 0
const v = c === 'x' ? r : (r & 0x3) | 0x8
return v.toString(16)
})
}
stackoverflow 上面的一个,更加标准一点:
export function uuid() {
// http://www.ietf.org/rfc/rfc4122.txt
const s = new Array(36);
const hexDigits = '0123456789abcdef';
for (let i = 0; i < 36; i++) {
const star = Math.floor(Math.random() * 0x10);
s[i] = hexDigits.substring(star, star + 1);
}
s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
// eslint-disable-next-line no-bitwise
const star = (s[19] & 0x3) | 0x8; // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[19] = hexDigits.substring(star, star + 1);
s[23] = '-';
s[18] = '-';
s[13] = '-';
s[8] = '-';
return s.join('');
}