I want to write a program that receives a list of numbers, converts them into an array, and output the even numbers in the array with Modulus Operator and For Loop.
The code does not run as expected:
JavaScript
x
11
11
1
function even_num(){
2
var submission = prompt("Enter Numbers:", ""); // receive list of numbers
3
var subarray = submission.split(''); // convert to array
4
5
for(var i =1; i < subarray.length; i++){
6
7
if( subarray[i] % 2 != 0){
8
document.getElementById("return").innerHTML += subarray[i] + ",";
9
}
10
}
11
}
JavaScript
1
2
1
<button onclick="even_num()">Even Number in an Array</button>
2
<p id = "return"></p>
Thank you
Advertisement
Answer
It’s a matter of incorrect condition.
i % 2
would give 0
for even numbers
JavaScript
1
11
11
1
function even_num() {
2
let submission = prompt("Enter Numbers:", "");
3
let subarray = submission.split('');
4
const result = document.getElementById("return");
5
result.innerHTML = '';
6
for (var i = 0; i < subarray.length; i++) {
7
if (subarray[i] % 2 == 0) {//Condition here was incorrect
8
result.innerHTML += subarray[i] + ",";
9
}
10
}
11
}
JavaScript
1
5
1
<html>
2
<button onclick="even_num()">Even Number in an Array</button>
3
<p id="return"></p>
4
5
</html>