I'm currently working on this task:
Create a JavaScript function that prompts the user for a number and then displays how many times that number appears in an array.
To achieve this, I am using parseFloat
to convert the user input from a string to a number. I have also defined my own array with a set of numbers.
function repeatNumber() {
const number = parseFloat(document.getElementById("number").value);
const myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let compare = false;
let count = 0;
for (let i = 0; i < myArray.length; i++) {
if (myArray[i] === number) {
compare = true;
count++;
}
}
//compare is where the result will be displayed
const repeating = document.getElementById("compare");
repating.textContent = "Is your number in my array ?" + compare;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<meta name="viewport" content="width=device-width, initial-scale=1.0>
<script src="/controlFlow/script.js"></script>
<title>Js>
</head>
<body>
<label for="number">Please enter a number to check its presence in my array</label>
<input type="text" id="number">
<button onclick="repeatNumber()">Check</button>
<p id="compare"> </p>
</body>
</html>