微信小程序 - 随機生成訂單号(JavaScript)
發表時(shí)間:2020-10-1
發布人(rén):融晨科技
浏覽次數:209
前言
如題,随機生成訂單号是(shì)很常見的(de)需求,如下圖所示:
第一種
可自己拼接其他(tā)字母。
時(shí)間戳 + 6位随機數的(de)訂單号。
function orderCode()
{
// 存放訂單号
let orderCode = '';
// 6位随機數(加在(zài)時(shí)間戳後面)
for (var i = 0; i < 6; i++)
{
orderCode += Math.floor(Math.random() * 10);
}
// 時(shí)間戳(用來(lái)生成訂單号)
orderCode = 'D' + new Date().getTime() + orderCode;
// 打印
console.log(orderCode)// D1601545805958923658
}
第二種
日期 + 6位随機數的(de)訂單号。
function setTimeDateFmt(s) { // 個(gè)位數補齊十位數
return s < 10 ? '0' + s : s;
}
function randomNumber() {
const now = new Date()
let month = now.getMonth() + 1
let day = now.getDate()
let hour = now.getHours()
let minutes = now.getMinutes()
let seconds = now.getSeconds()
month = setTimeDateFmt(month)
day = setTimeDateFmt(day)
hour = setTimeDateFmt(hour)
minutes = setTimeDateFmt(minutes)
seconds = setTimeDateFmt(seconds)
let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
console.log(orderCode)
return orderCode;
}
結果:
20190909103109582536