Confusing Key and Element in the for Loop in JavaScript
Let an array with month names be given:
let arr = [
'янв', 'фев', 'март', 'апр', 'май', 'июнь',
'июль', 'авг', 'сен', 'окт', 'ноя', 'дек'
];
Let the variable month store
the number of the current month:
let month = 10;
Let's use a loop to display all months, while the current month will be displayed in italics.
A certain programmer has already solved this problem,
however, he made a mistake and did not pay attention
to the fact that the variable month
stores the month number, not its name:
for (let i = 0; i < arr.length; i++) {
if (month === arr[i]) { // error here
document.write('<i>' + arr[i] + '</i>');
}
else {
document.write(arr[i]);
}
document.write('<br>');
}
Our programmer compares the array element
with the variable month. But this
variable stores the month number,
not its name!
For the code to work correctly,
you need to compare month
with the month number, that is,
with the value of the counter i:
for (let i = 0; i < arr.length; i++){
if (month === i) { // fixed the error
document.write('<i>' + arr[i] + '</i>');
}
else {
document.write(arr[i]);
}
document.write('<br>');
}