JavaScript

Dernière mise à jour : 26/05/2016

Type des variables

Énoncé

Déclarez trois variables a, b et c comme "1", "2" et a+b. Afficher le type et la valeur de chaque variable. Ensuite, forcez le type de a et b à entier et exécuter à nouveau a+b. Afficher le type et la valeur de chaque variable.

Solution

Fichier "js/script.js"

a = "1";
b = "2";
c = a + b;

document.writeln("Type et valeur des variables:");
document.writeln("-----------------------------");
document.writeln("  a: ("+typeof(a)+") "+a);
document.writeln("  b: ("+typeof(b)+") "+b);
document.writeln("  c: ("+typeof(c)+") "+c);

document.writeln("");

a = parseInt(a);
b = parseInt(b);
c = a + b;

document.writeln("Type et valeur des variables:");
document.writeln("-----------------------------");
document.writeln("  a: ("+typeof(a)+") "+a);
document.writeln("  b: ("+typeof(b)+") "+b);
document.writeln("  c: ("+typeof(c)+") "+c);

Fichier "index.html"

<!DOCTYPE html>
<html lang="fr">
  <head>
    <meta author="Sébastien Adam">
    <meta charset="UTF-8">
    <meta name="language" content="fr">
    <title>Type des variables</title>
  </head>
  <body>
    <pre>
<script type="text/javascript" src="js/script.js"></script>
    </pre>
  </body>
</html>