Funciones y Bucles
Este ejemplo muestra cómo usar funciones y bucles en TypeScript y su equivalente en JavaScript.
Ejemplo 1
// TypeScript
function sumarNumeros(numeros: number[]): number {
let suma: number = 0;
let i: number = 0;
while (i < numeros.length) {
suma += numeros[i];
i++;
}
return suma;
}
let numeros: number[] = [1, 2, 3, 4, 5];
document.addEventListener("DOMContentLoaded", function() {
document.body.innerHTML += `La suma de los números es: ${sumarNumeros(numeros)}
`;
});
// JavaScript
function sumarNumeros(numeros) {
let suma = 0;
let i = 0;
while (i < numeros.length) {
suma += numeros[i];
i++;
}
return suma;
}
let numeros = [1, 2, 3, 4, 5];
document.addEventListener("DOMContentLoaded", function() {
document.body.innerHTML += `La suma de los números es: ${sumarNumeros(numeros)}
`;
});
Ejemplo 2
// TypeScript
function contarVocales(texto: string): number {
let vocales: string = "aeiouAEIOU";
let contador: number = 0;
for (let i: number = 0; i < texto.length; i++) {
if (vocales.indexOf(texto[i]) !== -1) {
contador++;
}
}
return contador;
}
let texto: string = "Hola Mundo";
document.addEventListener("DOMContentLoaded", function() {
document.body.innerHTML += `El texto "${texto}" tiene ${contarVocales(texto)} vocales.
`;
});
// JavaScript
function contarVocales(texto) {
let vocales = "aeiouAEIOU";
let contador = 0;
for (let i = 0; i < texto.length; i++) {
if (vocales.indexOf(texto[i]) !== -1) {
contador++;
}
}
return contador;
}
let texto = "Hola Mundo";
document.addEventListener("DOMContentLoaded", function() {
document.body.innerHTML += `El texto "${texto}" tiene ${contarVocales(texto)} vocales.
`;
});
Ejemplo 3
// TypeScript
function esPrimo(num: number): boolean {
if (num <= 1) return false;
for (let i: number = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
let numero: number = 7;
document.addEventListener("DOMContentLoaded", function() {
document.body.innerHTML += `El número ${numero} es primo: ${esPrimo(numero)}
`;
});
// JavaScript
function esPrimo(num) {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
let numero = 7;
document.addEventListener("DOMContentLoaded", function() {
document.body.innerHTML += `El número ${numero} es primo: ${esPrimo(numero)}
`;
});