如何在JavaScript中生成随机十六进制字符串

问题描述:

如何生成仅包含给定长度的十六进制字符(0123456789abcdef)的随机字符串?

How to generate a random string containing only hex characters (0123456789abcdef) of a given length?

使用扩展运算符和 .map()

const genRanHex = size => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');

console.log(genRanHex(6));
console.log(genRanHex(12));
console.log(genRanHex(3));

  1. 输入一个数字( size )作为返回字符串的长度.

  1. Pass in a number (size) for the length of the returned string.

定义一个空数组( result )和一个字符串数组,其范围为 [0-9] [af] 代码>( hexRef ).

Define an empty array (result) and an array of strings in the range of [0-9] and [a-f] (hexRef).

for 循环的每次迭代中,生成一个0到15的随机数,并将其用作步骤2的字符串数组中值的索引( hexRef)-然后 push()将该值从步骤2( result )返回到空数组.

On each iteration of a for loop, generate a random number 0 to 15 and use it as the index of the value from the array of strings from step 2 (hexRef) -- then push() the value to the empty array from step 2 (result).

将数组( result )返回为 join('')字符串.

Return the array (result) as a join('')ed string.


演示2

const getRanHex = size => {
  let result = [];
  let hexRef = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];

  for (let n = 0; n < size; n++) {
    result.push(hexRef[Math.floor(Math.random() * 16)]);
  }
  return result.join('');
}

console.log(getRanHex(6));
console.log(getRanHex(12));
console.log(getRanHex(3));