Skip to content

標籤: JS

如何在JavaScript中產生UUID

function _uuid() {
var d = Date.now();
if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
d += performance.now(); //use high-precision timer if available
}
return '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);
});
}
view raw uuid.js hosted with ❤ by GitHub

如果只需兼容現代瀏覽器(Chrome)的話, 可以更簡易地使用…

function uuid2() {
return window.crypto.randomUUID();
}
view raw uuid2.js hosted with ❤ by GitHub

目前應該只有內核為Chromium的瀏覽器有支援到, 就是Chrome, Edge等等, 其他瀏覽器的支援程度可以看看這邊.