Curso Practico de Javascript 2
Curso Practico de Javascript 2
- Variables
- Declaración de variables
Una variable se puede declarar en JavaScript, de dos formas:
Forma Explícita: var nombre Variable;
Forma Implícita: var nombre Variable= valor;
<HTML>
<SCRIPT LANGUAGE=''JavaScript''
// PROG004.HTM
/* Programa que utiliza una variable explícita
y dos implícitas */
var Expli;
var pi=3.141592;
var radio=7;
Expli=pi*radio*radio;
alert("Área del Círculo = "+Expli);
</SCRIPT>
</HTML>
- Ejecútalo
4.- Tipos de Datos
Cuando declaramos una variable, ésta no pertenece a ningún tipo de dato en concreto, se dice que es
Undefined. Es al asignarle un valor cuando pasa a ser de uno u otro tipo, según el dato que albergue.
/ PROG005.HTM
var Pepe;
var PEPE="Hola que tal
"; var pepE=75.47;
var pEpe=" ¿Como estás?";
Pepe=PEPE+pEpe;
alert("PEPE="+PEPE);
alert("PEPE es "+typeof(PEPE));
alert("pepE="+pepE);
alert("pepE es "+typeof(pepE));
alert("pEpe="+pEpe);
alert("pEpe es "+typeof(pEpe));
alert("Pepe="+Pepe);
alert("Pepe es "+typeof(Pepe));
</SCRIPT>
</HTML>
<html>
<head>
<title>Sumar dos Numeros JavaScript</title>
</head>
<body>
<fieldset>
<legend>Ingrese dos numeros</legend>
<label for="">Numero 1:</label>
<input type="text" id="txtN1">
<br><br>
<label for="">Numero 2:</label>
<input type="text" id="txtN2">
<br><br>
<input type="button" onclick="Sumar();" value="Calucular">
</fieldset>
</body>
<script>
function Sumar() {
var n1 = document.getElementById('txtN1').value;
var n2 = document.getElementById('txtN2').value;
var suma = parseInt(n1) / parseInt(n2);
alert("La suma es: "+suma)
}
</script>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>Sumar dos números</h1>
<p>Por favor, introduce dos números:</p>
<input id="num1"><br>
<input id="num2">
<button type="button" onclick="myFunction()">Sumar</button>
<p id="sumando"></p>
<script>
function myFunction() {
var x,y,suma,text;
x = document.getElementById("num1").value;
y = document.getElementById("num2").value;
if (isNaN(x) || isNaN(y)) {
text = "Es necesarios introducir dos números válidos";
} else {
//si no ponemos parseFloat concatenaría x con y
suma=parseFloat(x)/parseFloat(y);
text= suma;
}
document.getElementById("sumando").innerHTML = text;
}
</script>
</body>
</html>