UUID 常用於建立唯一識別碼。在瀏覽器中,可以用 JavaScript 隨機產生字串,模擬 UUID 的格式。
function getUuid() {
var chars = '0123456789abcdef'.split('');
var uuid = [];
for (var i = 0; i < 36; i++) {
if (i === 8) {
uuid.push('-');
} else if (i === 13) {
uuid.push('-');
} else if (i === 18) {
uuid.push('-');
} else if (i === 23) {
uuid.push('-');
} else if (i === 14) {
uuid.push('4');
} else if (i === 19) {
uuid.push(chars[Math.floor(Math.random() * 4) + 8]);
} else {
uuid.push(chars[Math.floor(Math.random() * 16)]);
}
}
return uuid.join('');
}
這個方法會產生 36 個字元組成的字串,包含四個連字號,並符合常見 UUID 版本 4 的格式特徵。若只需要簡單的唯一值,也可以縮短長度或改用其他隨機策略。

在實際專案中,若需要更嚴格的唯一性,建議搭配 timestamp、random 或 crypto API。但在一般前端場景中,這種純 JavaScript 寫法已足夠使用。