Les fonctions avec des tableaux
🪛Exemples de code
const pers = [
{
nom: "Dupont",
ville: "Evry",
sex: "f",
},
{
nom: "Brusel",
ville: "Belfort",
sex: "h",
},
{
nom: "Dupont",
ville: "PARIS",
sex: "f",
},
{
nom: "Durant",
ville: "Paris",
sex: "h",
},
];
// have fun with for of
function affiche(tab, callback) {
for (let [i, ele] of Object.entries(tab)) {
console.log(callback ? callback(ele, i) : `${i}->${ele.nom}`);
}
}
affiche(pers);
affiche(pers, ({ nom: name, ville: town }) => `${name} lives in ${town}`);
function afficheVille({ ville }, i) {
return `${i} : ${ville}`;
}
affiche(pers, afficheVille);
// transforme
function transf(array, fx) {
let passed = [];
for (let v of array) passed.push(fx(v));
return passed;
}
//
function civilite({ nom, sex }) {
return sex == "h" ? `Monsieur ${nom}` : `Madame ${nom}`;
}
const newT = transf(pers, civilite);
console.log(newT);
//
function normalise(pers) {
return (pers.ville = pers.ville.toUpperCase());
}
transf(pers, normalise);
console.table(pers);