Recently, I developed a code snippet that is capable of generating random 12-digit codes using Math.random and for-loops. Users can input the desired number of codes they want to generate on the web page.
However, I am facing an issue with storing these randomly generated codes in an array. The current implementation of the for-loop and Math.random function concatenates each digit sequentially, making it challenging to add the complete 12-digit code to the array. How can I modify the code to save the entire generated code in the array for future use?
I attempted using array.push without success. Instead, I resorted to displaying the numbers in the HTML DOM as output:
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
The above approach does not store the 12-digit code in a variable. Another unsuccessful try involved:
var codeNumber = "";
codeNumber += mathRandom;
This method only resulted in a single-digit value stored in the variable.
<input type="number" id="numberOfCodes">
<button onclick="codeGen()">Generate</button>
<div id="result"></div>
<script>
var numberOfCodes = document.querySelector("#numberOfCodes");
var arr = [];
function codeGen() {
x = numberOfCodes.value;
for (a = 0; a < x; a++) {
generate();
console.log("Generated code");
}
}
function generate() {
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
}
</script>
</div>
</body>
</html>
My goal is to find a solution so that the generated codes are successfully added to the array, allowing me to use them later on the webpage. Each unique 12-digit code should occupy its own place within the array.