[英]Explanation of syntax on GUID / UUID Function in JavaScript
I am quite new to JS and was going over the code for generating a GUID / UUID.我对 JS 很陌生,并且正在查看生成 GUID / UUID 的代码。
This is the code I found in this Stackoverflow question这是我在这个 Stackoverflow 问题中找到的代码
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());
What I am having trouble with is understanding this syntax:我遇到的问题是理解这种语法:
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
Can someone help me by explaining step by step what it does?有人可以通过逐步解释它的作用来帮助我吗?
Your support is much appreciated.非常感谢您的支持。
Regards问候
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
is the same as是相同的
var r = Math.random() * 16 | 0;
ie, create a random number in the range from 0-15 (or 0-f in hex) without decimal places.即,在0-15(或十六进制的0-f)范围内创建一个不带小数位的随机数。 You could also write this line as你也可以把这一行写成
var r = Math.floor(Math.random() * 16)
but | 0
但是| 0
| 0
is probably faster... And | 0
可能更快......而且
var v = c == 'x' ? r : (r & 0x3 | 0x8);
ie, depending on the value of the current character to replace (ie 'x' or 'y') use either r
or r | 0x3 | 0x8
即,根据要替换的当前字符的值(即“x”或“y”)使用r
或r | 0x3 | 0x8
r | 0x3 | 0x8
r | 0x3 | 0x8
as value for the current place. r | 0x3 | 0x8
作为当前位置的值。 The latter is because of specification of UUID version 4, that certain bits must have certain values.后者是因为 UUID 版本 4 的规范,某些位必须具有某些值。 See specs for details.有关详细信息,请参阅规格。
You can rewrite this line as follows您可以按如下方式重写此行
var v = 0;
if (c == 'x') v = r;
else v = r & 0x3 | 0x8
So v
is still a value between 0 and 15, which is than converted to a hex char (0 - f) with v.toString(16)
所以v
仍然是 0 到 15 之间的值,然后使用v.toString(16)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.