yeecai / front-end-trivia

My collection of knowledge about JS/React/Css...topic interested in Issues.
0 stars 0 forks source link

getUUid #61

Open yeecai opened 2 years ago

yeecai commented 2 years ago

https://segmentfault.com/q/1010000013838612/a-1020000013849783 https://blog.csdn.net/qq_39416311/article/details/102762635

function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0;//这里其实还有一个作用就是把r变成了整数
        var v = (c == 'x') ? r : (r&0x3|0x8);// 其实就是说x直接替换,y另外的用经过特殊处理的,这里的特殊处理就是 r&0x3|0x8 ,因为位运算有顺序,这样的值就限定在一个范围了,其范围就是二进制 1000-1011这样4个数字了,然后输出为8,9,A,B这样4个字符了。
        return v.toString(16);
    });
}
yeecai commented 2 years ago

const getUUID = () => { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { return (c === "x" ? (Math.random() 16) | 0 : (((Math.random() 16) | 0) & 0x3) | 0x8).toString(16); }); };

yeecai commented 2 years ago

const getUUID = () => { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { return (c === "x" ? (Math.random() 16) | 0 : (((Math.random() 16) | 0) & 0x3) | 0x8).toString(16); }); };