uniqid() in javascript/jquery?

前端 未结 8 1844
孤城傲影
孤城傲影 2021-01-02 09:58

what\'s the equivalent of this function in javascript:

http://php.net/manual/en/function.uniqid.php

Basically I need to generate a random ID that looks like:

相关标签:
8条回答
  • 2021-01-02 10:55
    function uniqId(prefix) {
        if (window.performance) {
            var s = performance.timing.navigationStart;
            var n = performance.now();
            var base = Math.floor((s + Math.floor(n))/1000);
        } else {
            var n = new Date().getTime();
            var base = Math.floor(n/1000);
        }   
        var ext = Math.floor(n%1000*1000);
        var now = ("00000000"+base.toString(16)).slice(-8)+("000000"+ext.toString(16)).slice(-5);
        if (now <= window.my_las_uid) {
            now = (parseInt(window.my_las_uid?window.my_las_uid:now, 16)+1).toString(16);
        }
        window.my_las_uid = now;
        return (prefix?prefix:'')+now;
    }
    

    it is generated on "the same" priciple as PHP's uniqId() - specifically encoded time in microseconds.

    0 讨论(0)
  • 2021-01-02 10:58

    I have been using this ...

    I use it exactly as I would if it where PHP. Both return the same result.

    function uniqid(a = "", b = false) {
        const c = Date.now()/1000;
        let d = c.toString(16).split(".").join("");
        while(d.length < 14) d += "0";
        let e = "";
        if(b){
            e = ".";
            e += Math.round(Math.random()*100000000);
        }
        return a + d + e;
    }
    
    0 讨论(0)
提交回复
热议问题