I found myself a problem. I want to print an array from number 0 to 100.
if the number is divisible by 3, I want to print flip.
if the number is divisible by 5, I want to print flop.
for example the array should be [0,1,2,’flip’,4,’flop’,’flip,……..,’flop’].
How to do this in JS?
So far I have done this but it doesn’t print the whole array.
function wow() {
var arr = []
for (let i = 0; i <= 100; i++) {
if(i!=0){
if(i%3===0){
i='flip'
arr.push(i)
}
if(i%5===0){
i='flop'
arr.push(i)
}
}
arr.push(i)
}
console.log(arr)
}
wow()
>Solution :
You’re changing the variable i within the for loop which you shouldn’t be doing. Try using a temp variable for determining what gets pushed to your array.
Also, if a number is divisible by 3 AND 5 then the latter (flop) takes precedent, is that what you expect to happen?
function wow() {
var arr = []
for (let i = 0; i <= 100; i++) {
let temp = i;
if (i != 0) {
if (i % 3 === 0) {
temp = 'flip'
}
if (i % 5 === 0) {
temp = 'flop'
}
}
arr.push(temp)
}
console.log(arr);
}