The Missing Flag in JavaScript Loop Error
Let's say we have a certain number:
let num = '12345';
Let's check if this number contains a given digit. A certain programmer has already written code implementing this:
for (let digit of num) {
if (digit === '3') {
console.log('есть');
} else {
console.log('нет');
}
}
However, this code works incorrectly,
outputting 'есть' or 'нет'
for each array element.
We need the result to be output
only once. In this case, when combined
with a loop, the problem can only be solved using a flag:
let hasDigit = false; // flag
for (let digit of num) {
if (digit === '3') {
hasDigit = true;
break;
}
}
if (hasDigit) {
console.log('есть');
} else {
console.log('нет');
}