js生成唯一标识符(即唯一码)

上传文件到七牛云或其他服务器,有的会用到唯一码;
直接返回唯一码codeId,在需要的页面文件中引入,然后直接调用,用变量来接收即可~
注意:我用的是uni-app,在小程序环境中运行出现了问题,这里用条件编译来区分H5平台;
如果不需要// #ifdef H5 和 // #endif 去掉就可以了~

/**
 - 获取唯一码
 - @returns {string} 
 */
export function getUniqueCode() {
    
    
    let data = new Date().getTime();
	// #ifdef H5
    if (window.performance && typeof window.performance.now === "function") {
    
    
    // #endif
        data += performance.now(); // This uses performance.now() if it is available,
    // #ifdef H5
    }
    // #endif
    let codeId = 'xxxxxxxxxxxx6xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (msg) {
    
    
        let rand = (data + Math.random() * 16) % 16 | 0;
        data = Math.floor(data / 16);
        return (msg == 'x' ? rand : (rand & 0x3 | 0x8)).toString(16);
    });
    return codeId;
}

这里用到了performance.now();
看了些资料都说这个精确度比Date.now()高,两者的区别。
window.performance.now():返回的时间戳没有被限制在一毫秒的精确度内,是以一个恒定的速率慢慢增加的,它不会受到系统时间的影响(系统时钟可能会被手动调整或被NTP等软件篡改;附上MDN Web 文档链接
performance.now():是关联于页面加载,量级上精度更高,适用于高进度需求的场景。比如作为一个基准点或则游戏、音频、视频等所需精度很高的地方。但是值得注意的是: 它只适用于较新的浏览器(包括IE10 +);附上兼容性链接
Date.now():是Unix时间(1970-01-01T00:00:00Z)同时依靠系统时间,会因为系统时间的变化而改变,准确性有时不能保证,通用性比较高,没有兼容性问题;返回从1970年1月1日00:00:00 UTC开始经过的毫秒数;

  • 优缺点:
    1、performance.now()精确度高,不依靠系统时间,但是有兼容性问题;
    2、Date.now()受系统时间影响,并且以Unix时间为基准,不易看懂,但是没有兼容性问题;

如有错误或不足,欢迎各位大佬评论指正。

猜你喜欢

转载自blog.csdn.net/weixin_44711440/article/details/115518646