I’m trying to solve this exercise:
Write a JavaScript code that asks the user for a number and then print the number of times that number appears in an array.
I’m doing it with parseFloat
so I can get the string from the user with a <input />
and change it to number, then I declared my own array with 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 < number.length; i++) {
if (myArray[i] === number) {
compare = true;
count++;
}
}
//compare is my id in a p tag where i'll show the result
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</title>
</head>
<body>
<label for="number">Pls place a number to see if it's in my array</label>
<input type="text" id="number">
<button onclick="repeatNumber()">Check</button>
<p id="compare"> </p>
</body>
</html>
3
Answers
Maybe try this
It looks like there are a few issues in your code. You’re trying to loop through the
number
, but it should be an array, not a string. You also have a typo inrepeating
and a logical issue in the comparison. Here’s a corrected version of your code:In this corrected code:
myArray
and compared each element with theinputNumber
.count
variable to keep track of how many times the number appears in the array.repeating
element’s text content to display the count.