In: Computer Science
How do you write JavaScript codes to randomly select five elements by using a single for-loop? How do you display the results to a html page?
var password = [“x”, “y”, “z”, “1”, “2”, “3”, “test”];
Sample output:
zx21y |
HTML file :
<!DOCTYPE html>
<html lang="en">
<head>
<!-- -->
<title>Javascript elements</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- script is used for javascript -->
<script>
//Javascript array
var password = ["x", "y", "z", "1", "2", "3", "test"];
//using for loop
for (var i = 0; i < 5; i++) {
//randomly generate a number from 0 to array length
var randomNumber = Math.floor((Math.random() * password.length - 1) + 1);
//print the numbers on the web page
document.write(password[randomNumber]);
}
</script>
</body>
</html>
=========================================
Screen showing random numbers :