I have a script that includes a for-loop that generates the numbers 0-9. The script also includes a function that checks if the numbers generated by the for-loop are divisible by 3 or 5. If they are divisible (e.g. 9 is divisible by 3), the if/else-statement returns true, and if they are not divisible, the conditional-statement returns false.
What I want to achieve is that, when the conditional statement returns true, the number should be added to an empty array.
The desired result would in this case be:
var myArray = [0, 3, 5, 6, 9];
This is my current code:
var isDivisibleArray = [];
for(var i = 0; i < 10; i++) {
isMultiple(i);
}
function isMultiple() {
var isMultipleOf3 = i % 3;
var isMultipleOf5 = i % 5;
if(isMultipleOf3 === 0 || isMultipleOf5 === 0) {
return true;
}
else {
return false;
}
}
isMultiple();
I am using the modulus operator to find out if a number is divisible with 3 or 5, since if x % 3 = 0, x is divisible with 3, as an example.
I have done some experimenting as well. If I do this is the for-loop, I can manage to print the outcome using an alert:
for(var i = 0; i < 10; i++) {
alert(isMultiple(i));
}
The outcome is T, F, F, T, F, T, T, F, F, T.
I have also tried this approach within the conditional statement:
if(isMultipleOf3 === 0 || isMultipleOf5 === 0) {
isDivisibleArray.push(i);
}
This has not succeeded. All help would be much appreciated!
Aucun commentaire:
Enregistrer un commentaire