Problem with For Loop

Can someone help me figure out the difference between the function afficher() using for...in vs the for loop? Using for..in the output is correct but with for it's not. am I missing something?
function afficher(tab, n = 10) {
let output = "";
for (let i = 0; i < tab.length; i++) {
if (tab[i] % n == 0) {
output += "\n";
}
output += tab[i] + " ";
}
return output;
}

function createArray(nbr, max) {
let tab = [];
for(let i = 0; i < nbr; i++) {
let x = Math.floor(Math.random() * max);
tab.push(x);
}
return tab;
}

let tableau = createArray(6, 10);
console.log(afficher(tableau, 4));
function afficher(tab, n = 10) {
let output = "";
for (let i = 0; i < tab.length; i++) {
if (tab[i] % n == 0) {
output += "\n";
}
output += tab[i] + " ";
}
return output;
}

function createArray(nbr, max) {
let tab = [];
for(let i = 0; i < nbr; i++) {
let x = Math.floor(Math.random() * max);
tab.push(x);
}
return tab;
}

let tableau = createArray(6, 10);
console.log(afficher(tableau, 4));
function afficher(tab, n = 10) {
let output = "";
for (index in tab) {
if (index % n == 0) {
output += "\n";
}
output += tab[index] + " ";
}
return output;
}

function createArray(nbr, max) {
let tab = [];
for(let i = 0; i < nbr; i++) {
let x = Math.floor(Math.random() * max);
tab.push(x);
}
return tab;
}

let tableau = createArray(6, 10);
console.log(afficher(tableau, 4));
function afficher(tab, n = 10) {
let output = "";
for (index in tab) {
if (index % n == 0) {
output += "\n";
}
output += tab[index] + " ";
}
return output;
}

function createArray(nbr, max) {
let tab = [];
for(let i = 0; i < nbr; i++) {
let x = Math.floor(Math.random() * max);
tab.push(x);
}
return tab;
}

let tableau = createArray(6, 10);
console.log(afficher(tableau, 4));
3 Replies
WillsterJohnson
WillsterJohnson16mo ago
for (index in tab) a for..in loop will yield the index, wheras a for..of loop will get the value. The reason the second block is different is because
for (index in tab) {
if (index % n == 0) {
for (index in tab) {
if (index % n == 0) {
Means "if the index of the item modulo n is zero", whereas in the first block;
for (let i = 0; i < tab.length; i++) {
if (tab[i] % n == 0) {
for (let i = 0; i < tab.length; i++) {
if (tab[i] % n == 0) {
Means "if the item itself modulo n is zero" To fix the second block, you can use for (const tab of tabs) instead of for..in in short; for..in iterates keys (in an array that's the index) for..of iterates the values (in an array that's the items)
kooliris
kooliris16mo ago
Thank you! that was helpful
WillsterJohnson
WillsterJohnson16mo ago
np!