如何在JavaScript中生成随机十六进制字符串 [英] How to generate random hex string in javascript

查看:264
本文介绍了如何在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));

这篇关于如何在JavaScript中生成随机十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆