Exercices

Pour réaliser ces exercices, vous utiliserez l'interface HTML fournie (index.html) reliée au fichier JavaScript (script.js). N'ajoutez pas de balises HTML statiques : appuyez-vous sur les identifiants (id) et événements déjà présents dans le document. Pour observer les résultats dans la console, utilisez la touche F12 ou Ctrl+Maj+I.

1
<!doctype html>
2
<html lang="fr">
3
  <head>
4
    <meta charset="UTF-8" />
5
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
    <title>Exercices JavaScript - Partie 4</title>
7
8
    <script src="https://cdn.tailwindcss.com"></script>
9
    <script src="script.js" defer></script>
10
  </head>
11
12
  <body class="bg-slate-100 font-sans p-6 text-slate-800">
13
    <header class="max-w-4xl mb-4 mx-auto space-y-6">
14
      <h1 class="text-3xl font-bold text-slate-900 mb-2">
15
        Exercices JavaScript — Partie 4
16
      </h1>
17
18
      <p class="text-slate-600 text-sm">
19
        Objets, Programmation fonctionnelle, Web Storage &amp; Objets du noyau
20
      </p>
21
    </header>
22
23
    <main class="max-w-4xl mx-auto space-y-6">
24
      <!-- Ex 1 -->
25
      <section
26
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
27
      >
28
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
29
          Exercice 1 : Calcul de prix TTC via une méthode d'objet
30
        </h2>
31
32
        <button
33
          onclick="afficherPrixTTC()"
34
          class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg transition"
35
        >
36
          Calculer Prix TTC
37
        </button>
38
39
        <p id="details-produit" class="mt-3 font-medium"></p>
40
      </section>
41
42
      <!-- Ex 2 -->
43
      <section
44
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
45
      >
46
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
47
          Exercice 2 : Inspection des clés d'un objet (for...in)
48
        </h2>
49
50
        <button
51
          onclick="afficherConfig()"
52
          class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg transition"
53
        >
54
          Afficher la Configuration
55
        </button>
56
57
        <ul
58
          id="liste-config"
59
          class="mt-3 list-disc list-inside space-y-1 font-mono text-sm"
60
        ></ul>
61
      </section>
62
63
      <!-- Ex 3 -->
64
      <section
65
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
66
      >
67
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
68
          Exercice 3 : Augmentation globale des prix (.map)
69
        </h2>
70
71
        <button
72
          onclick="augmenterPrix()"
73
          class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg transition"
74
        >
75
          Augmenter les prix (+10%)
76
        </button>
77
78
        <section id="prix-augmentes" class="mt-3 font-mono text-sm"></section>
79
      </section>
80
81
      <!-- Ex 4 -->
82
      <section
83
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
84
      >
85
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
86
          Exercice 4 : Filtrage de produits en stock (.filter)
87
        </h2>
88
89
        <label class="flex items-center gap-2 cursor-pointer font-medium">
90
          <input
91
            type="checkbox"
92
            id="filtre-stock"
93
            onchange="filtrerStock()"
94
            class="w-4 h-4 text-blue-600 rounded"
95
          />
96
          Afficher uniquement les articles en stock
97
        </label>
98
99
        <section id="catalogue" class="mt-3 font-medium"></section>
100
      </section>
101
102
      <!-- Ex 5 -->
103
      <section
104
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
105
      >
106
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
107
          Exercice 5 : Calcul d'un total de panier (.reduce)
108
        </h2>
109
110
        <button
111
          onclick="calculerTotalPanier()"
112
          class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg transition"
113
        >
114
          Calculer le total du panier
115
        </button>
116
117
        <p id="total-panier" class="mt-3 font-semibold text-emerald-600"></p>
118
      </section>
119
120
      <!-- Ex 6 -->
121
      <section
122
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
123
      >
124
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
125
          Exercice 6 : Mémorisation d'un thème visuel (localStorage)
126
        </h2>
127
128
        <p class="flex gap-3">
129
          <button
130
            onclick="sauvegarderTheme('Sombre')"
131
            class="bg-slate-800 hover:bg-slate-900 text-white font-medium px-4 py-2 rounded-lg transition"
132
          >
133
            Thème Sombre
134
          </button>
135
136
          <button
137
            onclick="sauvegarderTheme('Clair')"
138
            class="bg-slate-200 hover:bg-slate-300 text-slate-800 font-medium px-4 py-2 rounded-lg transition"
139
          >
140
            Thème Clair
141
          </button>
142
        </p>
143
144
        <p id="theme-actif" class="mt-3 font-medium text-blue-600"></p>
145
      </section>
146
147
      <!-- Ex 7 -->
148
      <section
149
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
150
      >
151
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
152
          Exercice 7 : Restauration de saisie temporaire (sessionStorage)
153
        </h2>
154
155
        <textarea
156
          id="zone-note"
157
          oninput="sauvegarderBrouillon(this.value)"
158
          placeholder="Tapez votre note temporaire..."
159
          class="w-full border border-slate-300 rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-blue-500"
160
        ></textarea>
161
      </section>
162
163
      <!-- Ex 8 -->
164
      <section
165
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
166
      >
167
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
168
          Exercice 8 : Sauvegarde d'un profil complexe (JSON.stringify)
169
        </h2>
170
171
        <form
172
          onsubmit="sauvegarderProfil(event)"
173
          class="flex flex-wrap gap-3 items-center"
174
        >
175
          <input
176
            type="text"
177
            id="nom-user"
178
            placeholder="Nom"
179
            required
180
            class="border border-slate-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
181
          />
182
183
          <input
184
            type="number"
185
            id="age-user"
186
            placeholder="Âge"
187
            required
188
            class="border border-slate-300 rounded-lg px-3 py-2 w-24 focus:outline-none focus:ring-2 focus:ring-blue-500"
189
          />
190
191
          <button
192
            type="submit"
193
            class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg transition"
194
          >
195
            Enregistrer le profil
196
          </button>
197
        </form>
198
199
        <p
200
          id="confirmation-profil"
201
          class="mt-3 font-medium text-emerald-600"
202
        ></p>
203
      </section>
204
205
      <!-- Ex 9 -->
206
      <section
207
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
208
      >
209
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
210
          Exercice 9 : Lecture d'un profil (JSON.parse &amp; try...catch)
211
        </h2>
212
213
        <button
214
          onclick="lireProfil()"
215
          class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg transition"
216
        >
217
          Charger le profil
218
        </button>
219
220
        <p id="affichage-profil" class="mt-3 font-medium text-slate-800"></p>
221
      </section>
222
223
      <!-- Ex 10 -->
224
      <section
225
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
226
      >
227
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
228
          Exercice 10 : Pipeline complet (.filter, .map &amp; JSON)
229
        </h2>
230
231
        <button
232
          onclick="traiterEtudiants()"
233
          class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg transition"
234
        >
235
          Traiter et sauvegarder les admis
236
        </button>
237
238
        <p id="resultat-pipeline" class="mt-3 font-medium text-slate-800"></p>
239
      </section>
240
241
      <!-- Ex 11 -->
242
      <section
243
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
244
      >
245
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
246
          Exercice 11 : Calculs statistiques numériques (Math.min / Math.max)
247
        </h2>
248
249
        <button
250
          onclick="calculerExtremes()"
251
          class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg transition"
252
        >
253
          Extraire Min / Max
254
        </button>
255
256
        <section
257
          id="resultat-extremes-math"
258
          class="mt-3 font-mono text-sm"
259
        ></section>
260
      </section>
261
262
      <!-- Ex 12 -->
263
      <section
264
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
265
      >
266
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
267
          Exercice 12 : Horodatage et ID unique (Date.now)
268
        </h2>
269
270
        <button
271
          onclick="genererHorodatage()"
272
          class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg transition"
273
        >
274
          Générer Horodatage
275
        </button>
276
277
        <p
278
          id="affichage-horodatage"
279
          class="mt-3 font-mono text-sm text-slate-700"
280
        ></p>
281
      </section>
282
283
      <!-- Ex 13 -->
284
      <section
285
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
286
      >
287
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
288
          Exercice 13 : Calcul d'écart temporel (Date &amp; Math.floor)
289
        </h2>
290
291
        <button
292
          onclick="calculerEcartJours()"
293
          class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg transition"
294
        >
295
          Calculer l'écart avec le 01/01/2026
296
        </button>
297
298
        <p
299
          id="resultat-ecart-jours"
300
          class="mt-3 font-medium text-slate-800"
301
        ></p>
302
      </section>
303
304
      <!-- Ex 14 -->
305
      <section
306
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
307
      >
308
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
309
          Exercice 14 : Code de vérification aléatoire (Math.random)
310
        </h2>
311
312
        <button
313
          onclick="genererCodeVerification()"
314
          class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded-lg transition"
315
        >
316
          Générer Code
317
        </button>
318
319
        <p
320
          id="code-verification"
321
          class="mt-3 font-mono text-lg font-bold text-blue-600"
322
        ></p>
323
      </section>
324
325
      <!-- Ex 15 -->
326
      <section
327
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-200"
328
      >
329
        <h2 class="text-lg font-semibold text-slate-800 mb-3">
330
          Exercice 15 : Nettoyage du Storage (removeItem &amp; clear)
331
        </h2>
332
333
        <p class="flex gap-3">
334
          <button
335
            onclick="supprimerProfil()"
336
            class="bg-amber-600 hover:bg-amber-700 text-white font-medium px-4 py-2 rounded-lg transition"
337
          >
338
            Supprimer Profil
339
          </button>
340
341
          <button
342
            onclick="viderToutLeStorage()"
343
            class="bg-rose-600 hover:bg-rose-700 text-white font-medium px-4 py-2 rounded-lg transition"
344
          >
345
            Vider tout le Storage
346
          </button>
347
        </p>
348
349
        <p id="statut-nettoyage" class="mt-3 font-medium text-slate-700"></p>
350
      </section>
351
    </main>
352
  </body>
353
</html>
354

SyntaxeExercice 1 : Calcul de prix TTC via une méthode d'objet (onclick & this)

  • Créez un objet littéral produit possédant les propriétés nom ("Clavier"), prixHT (50) et une méthode calculerTTC() qui renvoie le prix augmenté de 20% de TVA via this.

  • Au clic sur le bouton, appelez cette méthode.

  • Affichez « Clavier : 60 € TTC » dans l'élément d'identifiant details-produit.

SyntaxeExercice 2 : Inspection des clés d'un objet (onclick & for...in)

  • Soit l'objet : const config = { theme: "sombre", langue: "fr", notifications: "activées" };.

  • Écrivez la fonction afficherConfig() qui parcourt l'objet avec une boucle for...in.

  • Injectez chaque paire clé/valeur sous forme d'élément de liste HTML dans l'élément liste-config.

SyntaxeExercice 3 : Augmentation globale des prix (onclick & .map)

  • Soit un tableau de prix : const prixHT = [10, 25, 50, 100];.

  • Au clic, utilisez la méthode .map() pour générer un nouveau tableau contenant les prix augmentés de 10%.

  • Affichez la liste des nouveaux prix séparés par des virgules dans l'élément prix-augmentes.

SyntaxeExercice 4 : Filtrage de produits en stock (onchange & .filter)

  • Soit un tableau d'objets représentants des articles : [{nom: "Livre", enStock: true}, {nom: "Stylo", enStock: false}, {nom: "Cahier", enStock: true}].

  • Lorsque la case à cocher est modifiée, utilisez la méthode .filter() pour isoler les articles disponibles.

  • Affichez uniquement les noms des articles en stock dans le conteneur catalogue.

SyntaxeExercice 5 : Calcul d'un total de panier (onclick & .reduce)

  • Soit le panier : [{nom: "Souris", prix: 20}, {nom: "Écran", prix: 150}, {nom: "Tapis", prix: 10}].

  • Écrivez la fonction calculerTotalPanier() qui utilise la méthode .reduce() pour sommer les prix des articles.

  • Affichez le message « Montant total : 180 € » dans l'élément d'identifiant total-panier.

SyntaxeExercice 6 : Mémorisation d'un thème visuel (onclick & localStorage)

  • Écrivez une fonction sauvegarderTheme(couleur) appelée au clic pour stocker le choix dans localStorage sous la clé "pref_theme".

  • Écrivez une fonction chargerTheme() exécutée au chargement pour lire la donnée sauvegardée.

  • Affichez le nom du thème actif dans l'élément theme-actif.

SyntaxeExercice 7 : Restauration de saisie temporaire (oninput & sessionStorage)

  • Écrivez la fonction sauvegarderBrouillon(valeur) déclenchée via l'événement oninput sur le champ zone-note.

  • Enregistrez la saisie dans sessionStorage sous la clé "brouillon_note".

  • Au rechargement de la page, restaurez automatiquement la valeur sauvegardée dans le champ texte s'il existe.

SyntaxeExercice 8 : Sauvegarde d'un profil complexe (onsubmit, JSON.stringify & localStorage)

  • À la soumission du formulaire, interceptez l'événement avec preventDefault() et construisez un objet profil à partir des champs nom-user et age-user.

  • Sérialisez l'objet au format JSON avec JSON.stringify().

  • Enregistrez la chaîne obtenue dans localStorage sous la clé "profil_utilisateur" et confirmez l'enregistrement dans confirmation-profil.

SyntaxeExercice 9 : Lecture et rechargement d'un profil (onclick, JSON.parse & try...catch)

  • Écrivez la fonction lireProfil() pour récupérer la clé "profil_utilisateur" depuis le localStorage.

  • Désérialisez la chaîne avec JSON.parse() à l'intérieur d'un bloc try...catch pour sécuriser la lecture.

  • Affichez le message « Bienvenue Alice (25 ans) » dans l'élément d'identifiant affichage-profil.

SyntaxeExercice 10 : Pipeline complet - Filtrer, transformer et sauvegarder (onsubmit, filter, map & JSON)

  • Soit le tableau d'étudiants : [{nom: "Luc", note: 14}, {nom: "Léa", note: 8}, {nom: "Mya", note: 16}].

  • Filtrez les étudiants admis (note >= 10) avec .filter() puis transformez le résultat en tableau de noms en majuscules via .map().

  • Sauvegardez la structure filtrée dans localStorage sous la clé "admis" en JSON et affichez le total dans resultat-pipeline.

SyntaxeExercice 11 : Calculs statistiques numériques (Math.min, Math.max & Spread)

  • Considérez un tableau de relevés numériques : [12.5, 42.0, 18.3, 29.9, 5.4].

  • Extrayez les valeurs minimale et maximale à l'aide des méthodes de l'objet Math combinées à l'opérateur spread (Math.min(...valeurs) et Math.max(...valeurs)).

  • Affichez les extrêmes trouvés dans le conteneur resultat-extremes-math.

SyntaxeExercice 12 : Horodatage et création d'identifiant unique (Date.now & toLocaleDateString)

  • Instanciez la date courante avec new Date() et générez un identifiant unique basé sur le temps grâce à Date.now().

  • Formatez la date en français avec la méthode toLocaleDateString('fr-FR').

  • Affichez l'identifiant et la date formatée dans l'élément affichage-horodatage.

SyntaxeExercice 13 : Calcul d'écart temporel en jours (Date & Math.floor)

  • Déclarez une date passée (ex: new Date("2026-01-01")) et récupérez la date actuelle.

  • Calculez la différence en millisecondes avec getTime() et convertissez-la en jours en la divisant par (1000 * 60 * 60 * 24).

  • Arrondissez le résultat à l'entier inférieur grâce à Math.floor() et affichez la durée écoulée dans resultat-ecart-jours.

SyntaxeExercice 14 : Génération d'un code de vérification aléatoire (Math.random & Math.floor)

  • Générez un nombre entier aléatoire compris entre 1000 et 9999 en combinant Math.random() et Math.floor().

  • Déclenchez cette génération lors du clic sur le bouton de l'exercice.

  • Injectez le code obtenu dans la zone d'affichage code-verification.

SyntaxeExercice 15 : Nettoyage et réinitialisation du Storage (localStorage.removeItem & clear)

  • Écrivez une fonction de suppression ciblée supprimant la clé "profil_utilisateur" avec localStorage.removeItem().

  • Écrivez une seconde fonction vidant l'ensemble du stockage local du domaine via localStorage.clear().

  • Mettez à jour le message de confirmation d'action dans l'élément d'identifiant statut-nettoyage.