js生成唯一的id(标识符)

责编:menVScode 2019-02-12 14:12 阅读(271)

需求:js生成不重复标识符 id。

方式一

var uuid = formatDateTime() + Math.random().toString(36).substr(2);

function formatDateTime() {
    var date = new Date();
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    return y + m + d + h + minute + second;
}

console.log(uuid) // 20190212142639jreyv1t83yd


方式二

function generateUUID() {
    var d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}
console.log( generateUUID() ) // f0ed305c-ec19-4967-b323-eef07a4cf2d8


标签: id 标识符 js
前端交流群: MVC前端网(menvscode.com)-qq交流群:551903636

邮箱快速注册

忘记密码