js生成订单号的几种方法
墨初 Web前端 2094阅读
对于网站集成了支付来说,如果将网站的支付在前端进行处理,就需要生成一个商家的唯一单号。下面的博文中73so博客说两个利用js脚本来生成订单号的方法。
js生成一个订单号都是结合当前的时间日期,结合日期可以大大的减少单号的生成率。
js生成订单号的方法
js时间戳加随机数生成订单号
例代码:
/**
* #JS生成订单号的函数
* @param
*
* @return string 生成的订单号
* @https://www.73so.com
*/
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());
// 1693104683523037769js日期加随机数生成订单号的方法
例代码:
function setTimeDateFmt(s) { // 个位数补齐十位数
return s < 10 ? '0' + s : s;
}
/**
* #JS生成订单号的函数
* @param
*
* @return string 生成的订单号
* @https://www.73so.com
*/
function createordernum()
{
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();
return orderCode;
}
console.log(createordernum());
// 20230827105534753003以上就是两种关于利用js脚本来生成订单号的方法,各位可以参考一下。