JavaScript GUID
软件程序使用全局唯一标识符或 guid
来唯一标识数据对象的位置。包括 guid
的一些数据示例是流媒体文件、Windows 注册表项、数据库密钥和各种其他文件类型。
在本教程中,我们将在 JavaScript 中创建一个 guid
。
在 JavaScript 中使用 math.random()
创建 guid
math.random()
函数返回 0 到 1 之间的十进制值,小数点后有 16 位数字(例如,0.2451923368509859)。然后我们可以根据所需的范围缩放这个随机值。
下面的例子展示了它在 JavaScript 中创建 guid
的实现。
var ID = function() {
return '_' + Math.random().toString(36).substr(2, 9);
};
Math.random().toString(36).slice(2);
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
console.log(uuidv4());
function uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
var userID = uuid();
输出:
315a0369-05c9-4165-8049-60e2489ea8e5
我们取一个字符串并使用此方法随机替换该字符串的字符以生成 guid
。
在 JavaScript 中使用正则表达式创建 guid
正则表达式是用于匹配字符串中字符组合的模式。它们是 JavaScript 中的对象。我们可以使用这些具有不同功能的模式来对字符串执行各种操作。
我们可以使用这样的模式在 JavaScript 中创建 guid
。
请参考下面的代码。
function create_UUID() {
var dt = new Date().getTime();
var uuid =
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (dt + Math.random() * 16) % 16 | 0;
dt = Math.floor(dt / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
console.log(create_UUID());
输出:
4191eebf-8a5b-4136-bfa0-6a594f4f0a03
请注意,在此方法中,我们还需要使用 Math.random()
函数,因为它确保每个输出都将返回一个唯一的 ID。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。