skip to Main Content

I would like to be able to generate 1 or a list of 10. It works, but I would like to have the option generate more than 1 at a time. The string must begin with 0x and have 16 characters after the 0x.

Here is a Fiddle
Please include the full code with output results instead of just the results in console.log

I added a second button to generate 10 and called it btn10. Then I tried tweaking the code to give different things a unique id, but must admit, I am completely lost.

const button = document.querySelector('#btn');
const hexValues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
const value = document.querySelector('.hexValue');

button.addEventListener('click', changeHex);

function changeHex() {
  let hex = '0x';

  for (let i = 0; i < 16; i++) {
    const index = Math.floor(Math.random() * hexValues.length)
    hex += hexValues[index];
  }

  value.textContent = hex;

}
<div class="container">
  <h1><span class="hexValue">Generate</span></h1>
  <button id="btn">Generate 1</button>
  <button id="btn5">Generate 5</button>
</div>

2

Answers


  1. Here is a version using delegation, map and template literals

    Study it and see if you can learn from it

    const container = document.getElementById('container');
    const hexValues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
    const output = document.querySelector('.hexValue');
    
    
    
    const getHex = () => `0x${Array.from({length:16}).map(_ => hexValues[Math.floor(Math.random() * 16)]).join('')}`;
    
    const generateHex = amount => Array.from({length:amount}).map(getHex); // create an array and map to the function (shorthand)
    
    container.addEventListener('click', (e) => { // delgating from the div
      const tgt = e.target.closest('.btn');
      if (!tgt) return; // not a button
      output.innerHTML = generateHex(+tgt.dataset.amount).join('n'); // the + is a unary plus converting the string to a number
    });
    <div id="container">
      <h1><pre class="hexValue">Generate</pre></h1>
      <button class="btn" data-amount="1">Generate 1</button>
      <button class="btn" data-amount="5">Generate 5</button>
    </div>
    Login or Signup to reply.
  2. const array = new BigUint64Array(1);
    self.crypto.getRandomValues(array)[0].toString(16).padStart(16, 'f');
    

    or

    ''.padStart(16, Math.random().toString(16).substring(2))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search