js生成唯一单号的方法
墨初 Web前端 1012阅读
javascript脚本可以通过时间戳,日期以及随机数等生成一个唯一的单号,下面提供了两个利用js脚本生成唯一单号的方法,大家可以参考使用。
js生成单号的方法
1、js利用时间戳加随机数的方式生成单号
例:
JavaScript
//生成订单单号
function orderCode() {
var orderCode='';
for (var i = 0; i < 6; i++) //6位随机数
{
orderCode += Math.floor(Math.random() * 10);
}
orderCode = new Date().getTime() + orderCode; //时间戳,用来生成订单号。
return orderCode;
}
console.log(orderCode());
// 1666497179212121716
2、js利用日期生成一个单事情
例:
JavaScript
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 = month < 10 ? "0" + month : month;
day = day < 10 ? "0" + day : day;
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
return orderCode;
}
console.log(randomNumber());
// 20221023115502674657
手机预览赞赏支持
"作者已被打赏56次"