I am trying to insert numbers from 1 to 15 into an array. And here is the code:
<html>
<head></head>
<body>
<button id="myBtn" value="HELLO">HELLO</button>
<script type="text/javascript">
var btn = document.getElementById("myBtn");
var num = null;
btn.addEventListener('click', function() {
var questions = new Array();
num = Math.floor(Math.random() * 14 + 2);
questions.push(num);
for (var i = 1; i <= 15; i++) {
num = Math.floor(Math.random() * 14 + 2);
if (questions.indexOf(num) !== -1) {
alert(num + " Exists in array. So not pushing it");
} else {
alert(num + " is not found. So pushing it");
questions.push(num);
}
console.log(questions);
}
alert(questions);
})
</script>
</body>
</html>
If you run this with the console open. You will notice that though a number is not in the array the in
operator still discards the number without pushing. Can I know why and how to correct this?
And also is there any better way to insert x number of numbers in random order each time.