Ejemplos de JavaScript


Tabla de contenido

    Mostrar tabla de contenidos


¿Qué puede hacer JavaScript?

JavaScript puede cambiar el contenido HTML

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button>

</body>
</html>

JavaScript puede cambiar los atributos HTML

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>
</html>

JavaScript puede cambiar el estilo CSS

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>

</body>
</html> 

JavaScript puede ocultar elementos HTML

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>

</body>
</html> 

JavaScript puede mostrar elementos HTML ocultos

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can show hidden HTML elements.</p>

<p id="demo" style="display:none">Hello JavaScript!</p>

<button type="button" onclick="document.getElementById('demo').style.display='block'">Click Me!</button>

</body>
</html> 

Ejemplos explicados


Dónde insertar JavaScript

JavaScript en

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h2>Demo JavaScript in Head</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html> 

JavaScript en

<!DOCTYPE html>
<html>
<body>

<h2>Demo JavaScript in Body</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html> 

JavaScript en un archivo externo

<!DOCTYPE html>
<html>
<body>

<h2>Demo External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>

<script src="myScript.js"></script>

</body>
</html>

JavaScript en una URL externa

<!DOCTYPE html>
<html>
<body>

<h2>External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Click Me</button>

<p>This example uses a full web URL to link to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>

<script src="https://www.w3schools.com/js/myScript.js"></script>

</body>
</html>

JavaScript en una carpeta externa

<!DOCTYPE html>
<html>
<body>

<h2>External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>This example uses a file path to link to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>

<script src="/js/myScript.js"></script>

</body>
</html>

Donde se explica


Salida de JavaScript

Escribir en la salida HTML

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>
<p>My first paragraph.</p>

<p>Never call document.write after the document has finished loading.
It will overwrite the whole document.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html> 

Escribir en un elemento HTML

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>
<p>My First Paragraph.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html> 

Escribir en un cuadro de alerta de ventana

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>
<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html> 

Escribiendo en la consola del navegador

<!DOCTYPE html>
<html>
<body>

<h2>Activate Debugging</h2>

<p>F12 on your keyboard will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>

<script>
console.log(5 + 6);
</script>

</body>
</html> 

Salida explicada


Sintaxis de JavaScript

Declaraciones de JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p>

<p id="demo"></p>

<script>
var x, y, z;  // Declare 3 variables
x = 5;    // Assign the value 5 to x
y = 6;    // Assign the value 6 to y
z = x + y;  // Assign the sum of x and y to z

document.getElementById("demo").innerHTML =
"The value of z is " + z + ".";
</script>

</body>
</html>

números de JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Number can be written with or without decimals.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 10.50;
</script>

</body>
</html>

cadenas de javascript

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>Strings can be written with double or single quotes.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 'John Doe';
</script>

</body>
</html>

variables de javascript

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>In this example, x is defined as a variable.
Then, x is assigned the value of 6:</p>

<p id="demo"></p>

<script>
let x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Operadores de JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Operators</h2>

<p>JavaScript uses arithmetic operators to compute values (just like algebra).</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = (5 + 6) * 10;
</script>

</body>
</html>

asignación de JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>Assigning JavaScript Values</h2>

<p>In JavaScript the = operator is used to assign values to variables.</p>

<p id="demo"></p>

<script>
let x, y;
x = 5;
y = 6;
document.getElementById("demo").innerHTML = x + y;
</script>

</body>
</html>

Expresiones de JavaScript (usando constantes)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Expressions</h2>

<p>Expressions compute to values.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 * 10;
</script>

</body>
</html>

Expresiones JavaScript (usando cadenas)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Expressions</h2>

<p>Expressions compute to values.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "John" + " "  + "Doe";
</script>

</body>
</html>

Expresiones de JavaScript (usando variables)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Expressions</h2>

<p>Expressions compute to values.</p>

<p id="demo"></p>

<script>
var x;
x = 5;
document.getElementById("demo").innerHTML = x * 10;
</script>

</body>
</html>

Palabras clave de JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>The var Keyword Creates Variables</h2>

<p id="demo"></p>

<script>
var x, y;
x = 5 + 6;
y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>

</body>
</html>

Comentarios de JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments are NOT Executed</h2>

<p id="demo"></p>

<script>
let x;
x = 5;
// x = 6; I will not be executed
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript distingue entre mayúsculas y minúsculas

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript is Case Sensitive</h2>

<p>Try to change lastName to lastname.</p>

<p id="demo"></p>

<script>
let lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
document.getElementById("demo").innerHTML = lastName;
</script>

</body>
</html>

Sintaxis explicada



Declaraciones de JavaScript

Las declaraciones de JavaScript son comandos para el navegador.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>In HTML, JavaScript statements are executed by the browser.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello Dolly.";
</script>

</body>
</html>

El código JavaScript es una secuencia de declaraciones.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p>

<p id="demo"></p>

<script>
let x, y, z;  // Statement 1
x = 5;        // Statement 2
y = 6;        // Statement 3
z = x + y;    // Statement 4

document.getElementById("demo").innerHTML =
"The value of z is " + z + ".";  
</script>

</body>
</html>

Las declaraciones de JavaScript están separadas por punto y coma

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>JavaScript statements are separated by semicolons.</p>

<p id="demo1"></p>

<script>
let a, b, c;
a = 5;
b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

</body>
</html>

Se permiten declaraciones múltiples en una línea

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>Multiple statements on one line are allowed.</p>

<p id="demo1"></p>

<script>
let a, b, c;
a = 5; b = 6; c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

</body>
</html>

Las declaraciones de JavaScript se pueden agrupar en bloques de código

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>JavaScript code blocks are written between { and }</p>

<button type="button" onclick="myFunction()">Click Me!</button>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
function myFunction() {
  document.getElementById("demo1").innerHTML = "Hello Dolly!";
  document.getElementById("demo2").innerHTML = "How are you?";
}
</script>

</body>
</html>

Puede dividir una línea de código después de un operador o una coma.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>
The best place to break a code line is after an operator or a comma.
</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Hello Dolly!";
</script>

</body>
</html>

Declaraciones explicadas


Comentarios de JavaScript

Comentarios de una sola línea

<!DOCTYPE html>
<html>
<body>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
// Change heading:
document.getElementById("myH").innerHTML = "JavaScript Comments";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

</body>
</html>

Comentarios de una sola línea al final de una línea

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>

<p id="demo"></p>

<script>
let x = 5;      // Declare x, give it the value of 5
let y = x + 2;  // Declare y, give it the value of x + 2 

// Write y to demo:
document.getElementById("demo").innerHTML = y;
</script>


</body>
</html>

Comentarios de varias líneas

<!DOCTYPE html>
<html>
<body>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML = "JavaScript Comments";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

</body>
</html>

Comentario de una sola línea para evitar la ejecución.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

<p>The line starting with // is not executed.</p>

</body>
</html>

Comentario de varias líneas para evitar la ejecución.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
/*
document.getElementById("myH").innerHTML = "Welcome to my Homepage";
document.getElementById("myP").innerHTML = "This is my first paragraph.";
*/
document.getElementById("myP").innerHTML = "The comment-block is not executed.";
</script>


</body>
</html>

Comentarios explicados


Variables de JavaScript

variables de javascript

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>


Variables de JavaScript como álgebra

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>In this example, price1, price2, and total are variables.</p>

<p id="demo"></p>

<script>
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
document.getElementById("demo").innerHTML =
"The total is: " + total;
</script>

</body>
</html>


Números y cadenas de JavaScript

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>Strings are written with quotes.</p>
<p>Numbers are written without quotes.</p>

<p id="demo"></p>

<script>
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

document.getElementById("demo").innerHTML =
pi + "<br>" + person + "<br>" + answer;
</script>

</body>
</html>


Palabra clave var de JavaScript.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>Create a variable, assign a value to it, and display it:</p>

<p id="demo"></p>

<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

Declarar muchas variables en una sola declaración

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>You can declare many variables in one statement.</p>

<p id="demo"></p>

<script>
let person = "John Doe", carName = "Volvo", price = 200;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>


Declarar muchas variables multilínea

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>You can declare many variables in one statement.</p>

<p id="demo"></p>

<script>
let person = "John Doe",
carName = "Volvo",
price = 200;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>


Una variable sin valor devuelve el valor indefinido

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>A variable without a value has the value of:</p>
<p id="demo"></p>

<script>
let carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>


Volver a declarar una variable no destruirá el valor

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>If you re-declare a JavaScript variable, it will not lose its value.</p>

<p id="demo"></p>

<script>
var carName = "Volvo";
var carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>


Agregar números de JavaScript

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The result of adding 5 + 2 + 3 is:</p>
<p id="demo"></p>

<script>
let x = 5 + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Agregar cadenas de JavaScript

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The result of adding "John" + " " + "Doe" is:</p>
<p id="demo"></p>

<script>
let x = "John" + " " + "Doe";
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Agregar cadenas y números

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The result of adding "5" + 2 + 3 is:</p>
<p id="demo"></p>

<script>
let x = "5" + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Variables explicadas


Aritmética de JavaScript

El operador de suma (+)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The + Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

El operador de resta (-)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The - Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x - y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

El operador de multiplicación (*)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The * Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x * y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

El operador de división (/)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The / Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x / y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

El operador de módulo (%)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The % Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x % y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

El operador de incremento (++)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>

<p>In this example, y is incremented before it is assigned to x (pre-incremented).</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var y = 5;
var x = ++y;
document.getElementById("demo1").innerHTML = y;
document.getElementById("demo2").innerHTML = x;
</script>

</body>
</html>

El operador de decremento (--)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>

<p>In this example, y is decremented before it is assigned to x (pre-decremented).</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var y = 5;
var x = --y;
document.getElementById("demo1").innerHTML = y;
document.getElementById("demo2").innerHTML = x;
</script>

</body>
</html>

Aritmética explicada


Asignación de JavaScript

El operador de asignación =

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The = Operator</h2>

<p id="demo"></p>

<script>
let x = 10;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

El operador de asignación +=

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The += Operator</h2>

<p id="demo"></p>

<script>
var x = 10;
x += 5;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

El operador de asignación -=

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The -= Operator</h2>

<p id="demo"></p>

<script>
var x = 10;
x -= 5;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

El operador de asignación *=

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The *= Operator</h2>

<p id="demo"></p>

<script>
var x = 10;
x *= 5;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

El operador de asignación /=

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The /= Operator</h2>

<p id="demo"></p>

<script>
var x = 10;
x /= 5;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

El operador de asignación %=

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The %= Operator</h2>

<p id="demo"></p>

<script>
var x = 10;
x %= 5;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Tarea explicada


Concatenación de cadenas de JavaScript

Sumar dos cadenas usando el operador de concatenación (+)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>

<p>The + operator concatenates (adds) strings.</p>

<p id="demo"></p>

<script>
var txt1 = "What a very";
var txt2 = "nice day";
document.getElementById("demo").innerHTML = txt1 + txt2;
</script>

</body>
</html>

Agregar dos cadenas juntas con un espacio en la primera cadena

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Operators</h2>
<h2>The + Operator</h2>
<p>The + operator concatenates (adds) strings.</p>

<p id="demo"></p>

<script>
let text1 = "What a very ";
let text2 = "nice day";
document.getElementById("demo").innerHTML = text1 + text2;
</script>

</body>
</html>

Agregar dos cadenas juntas con un espacio entre ellas

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Operators</h1>
<h2>The + operator</h2>
<p>The + operator concatenates (adds) strings.</p>

<p id="demo"></p>

<script>
var txt1 = "What a very";
var txt2 = "nice day";
document.getElementById("demo").innerHTML = txt1 + " " + txt2;
</script>

</body>
</html>

Sumar dos cadenas juntas usando el operador +=

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Operators</h1>
<h2>The += Operator</h2>
<p>The assignment operator += can concatenate strings.</p>

<p id="demo"></p>

<script>
let text1 = "What a very ";
text1 += "nice day";
document.getElementById("demo").innerHTML = text1;
</script>

</body>
</html>

Agregar cadenas y números

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Operators</h1>
<h2>The + Operator</h2>
<p>Adding a number and a string, returns a string.</p>

<p id="demo"></p>

<script>
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
document.getElementById("demo").innerHTML =
x + "<br>" + y + "<br>" + z;
</script>

</body>
</html>

Concatenación explicada


Tipos de datos de JavaScript

Declarar (crear) cadenas

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p>

<p id="demo"></p>

<script>
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';

document.getElementById("demo").innerHTML =
answer1 + "<br>" + 
answer2 + "<br>" + 
answer3;
</script>

</body>
</html>


Declarar (crear) números

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Numbers can be written with, or without decimals:</p>

<p id="demo"></p>

<script>
let x1 = 34.00;
let x2 = 34;
let x3 = 3.14;

document.getElementById("demo").innerHTML =
x1 + "<br>" + x2 + "<br>" + x3;
</script>

</body>
</html>


Declarar (crear) una matriz

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>Array indexes are zero-based, which means the first item is [0].</p>

<p id="demo"></p>

<script>
const cars = ["Saab","Volvo","BMW"];

document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>

Declarar (crear) un objeto

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
const person = {
  firstName : "John",
  lastName  : "Doe",
  age     : 50,
  eyeColor  : "blue"
};

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Encuentra el tipo de una variable.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>
<p>The typeof operator returns the type of a variable or an expression.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
typeof "" + "<br>" +
typeof "John" + "<br>" + 
typeof "John Doe" + "<br>" +
typeof 0 + "<br>" +
typeof 314 + "<br>" +
typeof 3.14 + "<br>" +
typeof (3.14);
</script>
</body>
</html>


Sumar dos números y una cadena

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript</h2>

<p>JavaScript evaluates expressions from left to right. Different sequences can produce different results:</p>

<p id="demo"></p>

<script>
let x = 16 + 4 + "Volvo";
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>


Agregar una cadena y dos números

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript</h2>

<p>JavaScript evaluates expressions from left to right. Different sequences can produce different results:</p>

<p id="demo"></p>

<script>
let x = "Volvo" + 16 + 4;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>


Una variable indefinida

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>
<p>The value (and the data type) of a variable with no value is <b>undefined</b>.</p>

<p id="demo"></p>

<script>
let car;
document.getElementById("demo").innerHTML =
car + "<br>" + typeof car;
</script>

</body>
</html> 

Una variable vacía

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript</h2>

<p>An empty string has both a legal value and a type:</p>

<p id="demo"></p>

<script>
let car = "";
document.getElementById("demo").innerHTML =
"The value is: " +
car + "<br>" +
"The type is: " + typeof car;
</script>

</body>
</html>


Tipos de datos explicados


Objetos JavaScript

Crear una variable de JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p id="demo"></p>

<script>
// Create and display a variable:
let car = "Fiat";
document.getElementById("demo").innerHTML = car;
</script>

</body>
</html>

Crear un objeto JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};

// Display some data from the object:
document.getElementById("demo").innerHTML = "The car type is " + car.type;
</script>

</body>
</html>

Crear un objeto persona (una sola línea)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Crear un objeto persona (varias líneas)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  age: 50,
  eyeColor: "blue"
};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Acceda a las propiedades del objeto usando .property

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>There are two different ways to access an object property.</p>

<p>You can use person.property or person["property"].</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName : "Doe",
  id     :  5566
};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>

</body>
</html>


Acceda a las propiedades del objeto usando [propiedad]

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>There are two different ways to access an object property.</p>

<p>You can use person.property or person["property"].</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName : "Doe",
  id     :  5566
};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person["firstName"] + " " + person["lastName"];
</script>

</body>
</html>


Acceder a una propiedad de función como método

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored as a property value.</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>

</body>
</html>

Acceder a una propiedad de función como propiedad

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>If you access an object method without (), it will return the function definition:</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName : "Doe",
  id     : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName;
</script>

</body>
</html>

Objetos explicados


Funciones de JavaScript

Una función sencilla

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World!";
}
</script>
</head>

<body>

<p>When you click "Try it", a function will be called.</p>
<p>The function will display a message.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

</body>
</html>

Una función con un argumento.

<!DOCTYPE html>
<html>
<body>

<p>Click "Try it" to call a function with arguments</p>

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<p id="demo"></p>

<script>
function myFunction(name,job) {
  document.getElementById("demo").innerHTML = "Welcome " + name + ", the " + job + ".";
}
</script>

</body>
</html>

Una función con un argumento 2.

<!DOCTYPE html>
<html> 
<head> 
<script> 
function myfunction(txt) { 
  document.getElementById("demo").innerHTML = txt
} 
</script> 
</head> 
<body> 

<p>When you click on one of the buttons, a function will be called. The function will display the argument that is passed to it.</p>

<form> 
  <input type="button" onclick="myfunction('Good Morning!')" value="In the Morning"> 
  <input type="button" onclick="myfunction('Good Evening!')" value="In the Evening"> 
</form> 

<p id="demo"></p>

</body> 
</html> 

Una función que devuelve un valor.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>

<p>Call a function which performs a calculation and returns the result:</p>

<p id="demo"></p>

<script>
let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b) {
  return a * b;
}
</script>

</body>
</html>

Una función que convierte Fahrenheit a Celsius

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>

<p>Invoke (call) a function that converts from Fahrenheit to Celsius:</p>
<p id="demo"></p>

<script>
function toCelsius(f) {
  return (5/9) * (f-32);
}

let value = toCelsius(77);
document.getElementById("demo").innerHTML = value;
</script>

</body>
</html>

Una llamada de función sin()

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>

<p>Accessing a function without () returns the function and not the function result:</p>
<p id="demo"></p>

<script>
function toCelsius(f) {
  return (5/9) * (f-32);
}

let value = toCelsius;
document.getElementById("demo").innerHTML = value;
</script>

</body>
</html>

Funciones explicadas


Eventos de JavaScript

Un evento onclick cambia un elemento HTML

<!DOCTYPE html>
<html>
<body>

<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>

<p id="demo"></p>

</body>
</html>

Un evento onclick cambia su propio elemento

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML Events</h2>
<button onclick="this.innerHTML=Date()">The time is?</button>

</body>
</html>

Un evento onclick llama a una función

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML Events</h2>
<p>Click the button to display the date.</p>

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>

</body>
</html> 

Eventos explicados


Cadenas de JavaScript

Las cadenas se pueden escribir con comillas simples o dobles.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>

<p>Strings are written inside quotes.</p>
<p>You can use single or double quotes:</p>

<p id="demo"></p>

<script>
var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';

document.getElementById("demo").innerHTML =
carName1 + " " + carName2; 
</script>

</body>
</html>


Mostrar algunos ejemplos de cadenas

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p>

<p id="demo"></p>

<script>
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';

document.getElementById("demo").innerHTML =
answer1 + "<br>" + 
answer2 + "<br>" + 
answer3;
</script>

</body>
</html>


La barra invertida antes de las comillas acepta comillas como comillas.

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>

var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north.";

document.getElementById("demo").innerHTML = x + "<br>" + y; 

</script>

</body>
</html>


Encuentra la longitud de una cuerda

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The length Property</h2>

<p>The length of the string is:</p>
<p id="demo"></p>

<script>
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = text.length;
</script>

</body>
</html>

Puedes dividir la cadena de texto con una barra invertida.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>

<p>
You can break a code line within a text string with a backslash.
</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
</script>

</body>
</html>

No se puede descifrar el código con una barra invertida.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p id="demo">You cannot break a code line with a \ backslash.</p>

<script>
document.getElementById("demo").innerHTML = \
"Hello Dolly.";
</script>

</body>
</html>

Reemplazar caracteres en una cadena - reemplazar()

<!DOCTYPE html>
<html>

<body>

<h1>JavaScript String Methods</h1>
<p>Replace &quot;Microsoft&quot; with &quot;W3Schools&quot; in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.replace("Microsoft","W3Schools");
}
</script>

</body>
</html>


Convertir cadena a mayúsculas - toUpperCase()

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Convert string to upper case:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.toUpperCase();
}
</script>

</body>
</html>

Convertir cadena a minúsculas - toLowerCase()

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Convert string to lower case:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.toLowerCase();
}
</script>

</body>
</html>

Dividir una cadena en una matriz - split()

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Display the first array element, after a string split:</p>

<p id="demo"></p>

<script>
let text = "a,b,c,d,e,f";
const myArray = text.split(",");
document.getElementById("demo").innerHTML = myArray[0];
</script>

</body>
</html>


Cuerdas explicadas


Números de JavaScript

Los números se pueden escribir con o sin decimales.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Numbers can be written with or without decimals:</p>

<p id="demo"></p>

<script>
let x = 3.14;
let y = 3;
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

</body>
</html>

Los números extra grandes o extra pequeños se pueden escribir con notación de exponentes.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Extra large or extra small numbers can be written with scientific (exponent) notation:</p>

<p id="demo"></p>

<script>
let x = 123e5;
let y = 123e-5;
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

</body>
</html>

Los números se consideran precisos solo hasta 15 dígitos

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>Integer Precision</h2>

<p>Integers (numbers without a period or exponent notation) are accurate up to 15 digits:</p>

<p id="demo"></p>

<script>
let x = 999999999999999;
let y = 9999999999999999;
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

</body>
</html>


La aritmética de coma flotante no siempre es 100% precisa

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>Floating Point Precision</h2>

<p>Floating point arithmetic is not always 100% accurate.</p>

<p id="demo"></p>

<script>
let x = 0.2 + 0.1;
document.getElementById("demo").innerHTML = "0.2 + 0.1 = " + x;
</script>

</body>
</html>


Pero ayuda multiplicar y dividir por 10.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Floating point arithmetic is not always 100% accurate:</p>
<p id="demo1"></p>

<p>But it helps to multiply and divide:</p>

<p id="demo2"></p>

<script>
let x = 0.2 + 0.1;
document.getElementById("demo1").innerHTML = "0.2 + 0.1 = " + x;
let y = (0.2*10 + 0.1*10) / 10;
document.getElementById("demo2").innerHTML = "0.2 + 0.1 = " + y;
</script>

</body>
</html>


Sumar dos números da como resultado un nuevo número

Agregar dos cadenas numéricas da como resultado una cadena concatenada

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>If you add two numeric strings, the result will be a concatenated string:</p>

<p id="demo"></p>

<script>
let x = "10";
let y = "20";
let z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>


Agregar un número y una cadena numérica también da como resultado una cadena concatenada

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>If you add a number and a numeric string, the result will be a concatenated string:</p>

<p id="demo"></p>

<script>
let x = 10;
let y = "20";
let z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>


Agregar una cadena numérica y un número también da como resultado una cadena concatenada

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>If you add a numeric string and a number, the result will be a concatenated string:</p>

<p id="demo"></p>

<script>
let x = "10";
let y = 20;
document.getElementById("demo").innerHTML = "The result is: " + x + y;
</script>

</body>
</html>


Error común al sumar cadenas y números 1

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>A common mistake is to expect this result to be 30:</p>

<p id="demo"></p>

<script>
var x = 10;
var y = 20;
document.getElementById("demo").innerHTML =
"The result is: " + x + y;
</script>

</body>
</html>


Error común al sumar cadenas y números 2

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>A common mistake is to expect this result to be 102030:</p>

<p id="demo"></p>

<script>
let x = 10;
let y = 20;
let z = "30";
let result = x + y + z;
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>


JavaScript intentará convertir cadenas en números al dividir

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>JavaScript will try to convert strings to numbers when dividing:</p>

<p id="demo"></p>

<script>
let x = "100";
let y = "10";
let z = x / y;   
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript intentará convertir cadenas en números al multiplicar

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>JavaScript will try to convert strings to numbers when multiplying:</p>

<p id="demo"></p>

<script>
let x = "100";
let y = "10";
let z = x * y;   
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript intentará convertir cadenas en números al restar

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>JavaScript will try to convert strings to numbers when subtracting:</p>

<p id="demo"></p>

<script>
let x = "100";
let y = "10";
let z = x - y;   
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript NO convertirá cadenas en números al agregar

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>JavaScript will NOT convert strings to numbers when adding:</p>

<p id="demo"></p>

<script>
let x = "100";
let y = "10";
let z = x + y;   
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

Un número dividido por una cadena es NaN (no es un número)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>A number divided by a non-numeric string becomes NaN (Not a Number):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 100 / "Apple";
</script>

</body>
</html>

Un número dividido por una cadena numérica es un número

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>A number divided by a numeric string becomes a number:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 100 / "10";
</script>

</body>
</html>

La función global de JavaScript isNaN() devuelve si un valor es un número

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>You can use the global JavaScript function isNaN() to find out if a value is not a number:</p>

<p id="demo"></p>

<script>
let x = 100 / "Apple";
document.getElementById("demo").innerHTML = isNaN(x);
</script>

</body>
</html>

Usar NaN en una operación matemática siempre devolverá NaN

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>If you use NaN in a mathematical operation, the result will also be NaN:</p>

<p id="demo"></p>

<script>
let x = NaN;
let y = 5;
document.getElementById("demo").innerHTML = x + y;
</script>

</body>
</html>

El uso de NaN en una operación matemática de cadena concatenará NaN

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>If you use NaN in a mathematical operation, the result can be a concatenation:</p>

<p id="demo"></p>

<script>
let x = NaN;
let y = "5";
document.getElementById("demo").innerHTML = x + y;
</script>

</body>
</html>

NaN (no es un número) es un número (¡Sí! typeof NaN devuelve un número)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>The typeof NaN is number:</p>

<p id="demo"></p>

<script>
let x = NaN;
document.getElementById("demo").innerHTML = typeof x;
</script>

</body>
</html>


Se devuelve infinito si calcula un número fuera del mayor número posible

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Infinity is returned if you calculate a number outside the largest possible number:</p>

<p id="demo"></p>

<script>
let myNumber = 2; 
let txt = "";
while (myNumber != Infinity) {
   myNumber = myNumber * myNumber;
   txt = txt + myNumber + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>


La división por cero también genera el Infinito

Infinito es un número (el tipo de Infinito devuelve un número)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Infinity is a number:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = typeof Infinity;
</script>

</body>
</html>


Las constantes, precedidas por 0x, se interpretan como hexadecimales.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Numeric constants, preceded by 0x, are interpreted as hexadecimal:</p>

<p id="demo"></p>

<script>
let x = 0xFF;
document.getElementById("demo").innerHTML = "0xFF = " + x;
</script>

</body>
</html>


El método toString() puede generar números en formato hexadecimal, octal y binario.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>The toString() method can output numbers from base 2 to 36:</p>

<p id="demo"></p>

<script>
let myNumber = 32;
document.getElementById("demo").innerHTML =
"Decimal 32 = " + "<br><br>" + 

"Hexatrigesimal (base 36): " + myNumber.toString(36) + "<br>" +
"Duotrigesimal (base 32): " + myNumber.toString(32) + "<br>" +
"Hexadecimal (base 16): " + myNumber.toString(16) + "<br>" +
"Duodecimal (base 12): " + myNumber.toString(12) + "<br>" +
"Decimal (base 10): " + myNumber.toString(10) + "<br>" +
"Octal (base 8): " + myNumber.toString(8) + "<br>" +
"Binary (base 2): " + myNumber.toString(2);
</script>

</body>
</html>

Los números pueden ser objetos.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p id="demo"></p>

<script>
// x is a number
let x = 123;

// y is a Number object
let y = new Number(123);

document.getElementById("demo").innerHTML = typeof x + "<br>" + typeof y;
</script>

</body>
</html>

Los números y los objetos no se pueden comparar de forma segura

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Numbers and Number objects cannot be safely compared:</p>

<p id="demo"></p>

<script>
// x is a number
let x = 500;

// y is an object
let y = new Number(500);

document.getElementById("demo").innerHTML = (x===y);
</script>

</body>
</html>

Los objetos y los objetos no se pueden comparar de forma segura.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>JavaScript objects cannot be compared:</p>

<p id="demo"></p>

<script>
// x is an object
let x = new Number(500);

// y is an object
let y = new Number(500);

document.getElementById("demo").innerHTML = (x==y);
</script>

</body>
</html>

Números explicados


Métodos numéricos de JavaScript

El método toString() convierte un número en una cadena

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>The toString() method can output numbers from base 2 to 36:</p>

<p id="demo"></p>

<script>
let myNumber = 32;
document.getElementById("demo").innerHTML =
"Decimal 32 = " + "<br><br>" + 

"Hexatrigesimal (base 36): " + myNumber.toString(36) + "<br>" +
"Duotrigesimal (base 32): " + myNumber.toString(32) + "<br>" +
"Hexadecimal (base 16): " + myNumber.toString(16) + "<br>" +
"Duodecimal (base 12): " + myNumber.toString(12) + "<br>" +
"Decimal (base 10): " + myNumber.toString(10) + "<br>" +
"Octal (base 8): " + myNumber.toString(8) + "<br>" +
"Binary (base 2): " + myNumber.toString(2);
</script>

</body>
</html>

El método valueOf() devuelve un número como un número

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The valueOf() method returns a number as a number:</p>

<p id="demo"></p>

<script>
let x = 123;

document.getElementById("demo").innerHTML = 
  x.valueOf() + "<br>" +
  (123).valueOf() + "<br>" +
  (100 + 23).valueOf();
</script>

</body>
</html>

toExponential() devuelve un número con notación exponencial

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The toExponential() method returns a string, with the number rounded and written using exponential notation.</p>

<p>An optional parameter defines the number of digits behind the decimal point.</p>

<p id="demo"></p>

<script>
let x = 9.656;
document.getElementById("demo").innerHTML =
  x.toExponential() + "<br>" + 
  x.toExponential(2) + "<br>" + 
  x.toExponential(4) + "<br>" + 
  x.toExponential(6);
</script>

</body>
</html>

El método toFixed() redondea un número a una cantidad de dígitos

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The toFixed() method rounds a number to a given number of digits.</p>
<p>For working with money, toFixed(2) is perfect.</p>

<p id="demo"></p>

<script>
let x = 9.656;
document.getElementById("demo").innerHTML =
  x.toFixed(0) + "<br>" +
  x.toFixed(2) + "<br>" +
  x.toFixed(4) + "<br>" +
  x.toFixed(6);
</script>

</body>
</html>

El método toPrecision() un número escrito con una longitud especificada

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The toPrecision() method returns a string, with a number written with a specified length:</p>

<p id="demo"></p>

<script>
let x = 9.656;
document.getElementById("demo").innerHTML = 
  x.toPrecision() + "<br>" +
  x.toPrecision(2) + "<br>" +
  x.toPrecision(4) + "<br>" +
  x.toPrecision(6);  
</script>

</body>
</html>

El método global Number() convierte variables en números

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Global Methods</h2>

<p>The Number() method converts variables to numbers:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
  Number(true) + "<br>" +
  Number(false) + "<br>" +
  Number("10") + "<br>" + 
  Number("  10") + "<br>" +
  Number("10  ") + "<br>" +
  Number(" 10  ") + "<br>" +
  Number("10.33") + "<br>" + 
  Number("10,33") + "<br>" +
  Number("10 33") + "<br>" +
  Number("John");
</script>

</body>
</html>


El método global Number() puede incluso convertir fechas en números

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Global Methods</h2>

<p>The Number() method can convert a date to a number:</p>

<p id="demo"></p>

<script>
let x = new Date("2017-09-30");
document.getElementById("demo").innerHTML = Number(x); 
</script>

</body>
</html>


El método global parseInt() convierte cadenas en números

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Global Functions</h2>
<h2>parseInt()</h2>
<p>The global JavaScript function parseInt() converts strings to numbers:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
  parseInt("-10") + "<br>" +
  parseInt("-10.33") + "<br>" +
  parseInt("10") + "<br>" +
  parseInt("10.33") + "<br>" +
  parseInt("10 6") + "<br>" +  
  parseInt("10 years") + "<br>" +  
  parseInt("years 10");  
</script>

</body>
</html>


El método global parseFloat() convierte cadenas en números

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Global Methods</h2>

<p>The parseFloat() method converts strings to numbers:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
  parseFloat("10") + "<br>" +
  parseFloat("10.33") + "<br>" +
  parseFloat("10 6") + "<br>" +  
  parseFloat("10 years") + "<br>" +
  parseFloat("years 10");    
</script>

</body>
</html>


MAX_VALUE devuelve el mayor número posible en JavaScript

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The MAX_VALUE Property</h2>

<p>The largest possible number in JavaScript is:</p>
<p id="demo"></p>

<script>
let x = Number.MAX_VALUE;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

MIN_VALUE devuelve el número más pequeño posible en JavaScript

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The MIN_VALUE Property</h2>

<p>The smallest number possible in JavaScript is:</p>
<p id="demo"></p>

<script>
let x = Number.MIN_VALUE;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

POSITIVE_INFINITY representa el infinito

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The POSITIVE_INFINITY Property</h2>

<p id="demo"></p>

<script>
let x = Number.POSITIVE_INFINITY;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

POSITIVE_INFINITY se devuelve en caso de desbordamiento

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The POSITIVE_INFINITY Property</h2>

<p>POSITIVE_INFINITY is returned on overflow:</p>
<p id="demo"></p>

<script>
let x = 1 / 0;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

NEGATIVE_INFINITY representa infinito negativo

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The NEGATIVE_INFINITY Property</h2>

<p></p>

<p id="demo"></p>

<script>
let x = Number.NEGATIVE_INFINITY;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

NEGATIVE_INFINITY se devuelve en caso de desbordamiento

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The NEGATIVE_INFINITY Property</h2>

<p>NEGATIVE_INFINITY is returned on overflow:</p>
<p id="demo"></p>

<script>
let x = -1 / 0;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

NaN representa "no es un número"

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Properties</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Number.NaN;
</script>

</body>
</html>

La aritmética realizada en una cadena dará como resultado NaN

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>A number divided by a non-numeric string becomes NaN (Not a Number):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 100 / "Apple";
</script>

</body>
</html>

El uso de una propiedad numérica en una variable devolverá un valor indefinido

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Number Properties</h1>

<p>Using a Number property on a variable, or value, will return undefined:</p>

<p id="demo"></p>

<script>
let x = 6;
document.getElementById("demo").innerHTML = x.MAX_VALUE;
</script>

</body>
</html>

Métodos numéricos explicados


Matemáticas JavaScript

Math.PI devuelve el valor de PI

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.PI</h2>

<p>Math.PI returns the ratio of a circle's circumference to its diameter:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.PI;
</script>

</body>
</html>

Math.round(x) devuelve el valor redondeado de x

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.round()</h2>

<p>Math.round(x) returns the value of x rounded to its nearest integer:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.round(4.5);
</script>

</body>
</html>

Math.pow(x, y) devuelve el valor de x elevado a y

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.pow()</h2>

<p>Math.pow(x,y) returns the value of x to the power of y:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.pow(8,2);
</script>

</body>
</html>

Math.sqrt(x) devuelve la raíz cuadrada de x

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.sqrt()</h2>

<p>Math.sqrt(x) returns the square root of x:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.sqrt(64);
</script>

</body>
</html>

Math.abs(x) devuelve el valor absoluto (positivo) de x

Math.ceil(x) devuelve el valor de x redondeado hacia arriba

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.ceil()</h2>

<p>Math.ceil() rounds a number <strong>up</strong> to its nearest integer:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.ceil(4.4);
</script>

</body>
</html>

Math.floor(x) devuelve el valor de x redondeado hacia abajo

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.floor()</h2>

<p>Math.floor(x) returns the value of x rounded <strong>down</strong> to its nearest integer:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.floor(4.7);
</script>

</body>
</html>

Math.sin(x) devuelve el pecado del ángulo x (dado en radianes)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.sin()</h2>

<p>Math.sin(x) returns the sin of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"The sine value of 90 degrees is " + Math.sin(90 * Math.PI / 180);
</script>

</body>
</html>

Math.cos(x) devuelve el coseno del ángulo x (dado en radianes)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.cos()</h2>

<p>Math.cos(x) returns the cosine of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"The cosine value of 0 degrees is " + Math.cos(0 * Math.PI / 180);
</script>

</body>
</html>

Math.max() devuelve el número con el valor más alto de una lista de argumentos

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.max()</h2>

<p>Math.max() returns the highest value in a list of arguments.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.max(0, 150, 30, 20, -8, -200);
</script>

</body>
</html>

Math.min() para devolver el número con el valor más bajo de una lista de argumentos

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.min()</h2>

<p>Math.min() returns the lowest value in a list of arguments:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.min(0, 150, 30, 20, -8, -200);
</script>

</body>
</html>

Convertir grados Celsius a Fahrenheit

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Celcius to Fahrenhet</h2>

<p>Insert a number into one of the input fields below:</p>

<p><input id="c" onkeyup="convert('C')"> degrees Celsius</p>

<p><input id="f" onkeyup="convert('F')"> degrees Fahrenheit</p> 

<p>Note that the <b>Math.round()</b> method is used, so that the result will be returned as an integer.</p>

<script>
function convert(degree) {
  var x;
  if (degree == "C") {
    x = document.getElementById("c").value * 9 / 5 + 32;
    document.getElementById("f").value = Math.round(x);
  } else {
    x = (document.getElementById("f").value -32) * 5 / 9;
    document.getElementById("c").value = Math.round(x);
  }
}
</script>

</body>
</html>

Matemáticas explicadas


JavaScript aleatorio

Math.random() devuelve un número aleatorio entre 0 (incluido) y 1 (excluido)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.random()</h2>

<p>Math.random() returns a random number between 0 (included) and 1 (excluded):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.random();
</script>

</body>
</html>

Cómo devolver un número entero aleatorio entre 0 y 9 (ambos incluidos)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor(Math.random() * 10) returns a random integer between 0 and 9 (both 
included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 10);
</script>

</body>
</html>

Cómo devolver un número entero aleatorio entre 0 y 10 (ambos incluidos)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor(Math.random() * 11) returns a random integer between 0 and 10 (both included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 11);
</script>

</body>
</html>

Cómo devolver un número entero aleatorio entre 0 y 99 (ambos incluidos)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor(Math.random() * 100)) returns a random integer between 0 and 99 
(both included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 100);
</script>

</body>
</html>

Cómo devolver un número entero aleatorio entre 0 y 100 (ambos incluidos)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor() used with Math.random() * 101 returns a random integer between 0 and 100 
(both included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 101);
</script>

</body>
</html>

Cómo devolver un número entero aleatorio entre 1 y 10 (ambos incluidos)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor(Math.random() * 10) + 1) returns a random integer between 1 and 10 
(both included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 10) + 1;
</script>

</body>
</html>

Cómo devolver un número entero aleatorio entre 1 y 100 (ambos incluidos)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor(Math.random() * 100) + 1) returns a random integer between 1 and 
100 (both included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 100) + 1;
</script>

</body>
</html>

Cómo devolver un número entero aleatorio entre x (incluido) e y (excluido)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.random()</h2>

<p>Every time you click the button, getRndInteger(min, max) returns a random number between 0 
and 9 (both included):</p>

<button onclick="document.getElementById('demo').innerHTML = getRndInteger(0,10)">Click Me</button>

<p id="demo"></p>

<script>
function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
</script>

</body>
</html>

Cómo devolver un número entero aleatorio entre xey (ambos incluidos)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.random()</h2>

<p>Every time you click the button, getRndInteger(min, max) returns a random number between 1 and 10 (both included):</p>

<button onclick="document.getElementById('demo').innerHTML = getRndInteger(1,10)">Click Me</button>

<p id="demo"></p>

<script>
function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}
</script>

</body>
</html>

Aleatorio explicado


Fechas de JavaScript

Utilice Date() para mostrar la fecha y hora de hoy

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Dates</h1>
<h2>Using new Date()</h2>
<p>new Date() without arguments, creates a date object with the current date and time:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>

Utilice getFullYear() para mostrar el año

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Dates</h1>
<h2>The getFullYear() Method</h2>
<p>Return the full year of a date object:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
</script>

</body>
</html>

Utilice getTime() para calcular el número de milisegundos desde 1970

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getTime() Method</h2>
<p></p>
<p>Return the number of milliseconds since midnight January 1, 1970:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
</script>

</body>
</html>

Utilice setFullYear() para establecer una fecha específica

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript setFullYear()</h2>
<p>The setFullYear() method sets the year of a date object:</p>

<p id="demo"></p>

<script>
const d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>

Utilice toUTCString() para convertir la fecha de hoy (según UTC) en una cadena

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Dates</h1>
<h2>The toUTCString() Method</h2>
<p>Convert a date to a string using the UTC standard:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
</script>

</body>
</html>

Utilice getDay() para mostrar el día de la semana como un número

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getDay() Method</h2>
<p>Return the weekday as a number:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
</script>

</body>
</html>

Utilice getDay() y una matriz para mostrar el día de la semana como nombre

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getDay() Method</h2>
<p>Return the weekday as a number.</p>
<p>You can use an array of names to return the weekday as a name:</p>

<p id="demo"></p>

<script>
const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

const d = new Date();
let day = days[d.getDay()];
document.getElementById("demo").innerHTML = day;
</script>

</body>
</html>

mostrar un reloj

<!DOCTYPE html>
<html>

<body onload="startTime()">

<h2>JavaScript Clock</h2>

<div id="txt"></div>

<script>
function startTime() {
  const today = new Date();
  let h = today.getHours();
  let m = today.getMinutes();
  let s = today.getSeconds();
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('txt').innerHTML =  h + ":" + m + ":" + s;
  setTimeout(startTime, 1000);
}

function checkTime(i) {
  if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
  return i;
}
</script>

</body>
</html>

Fechas explicadas


Matrices de JavaScript

Crear una matriz I

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

Crear una matriz II

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p id="demo"></p>

<script>
const cars = [
  "Saab",
  "Volvo",
  "BMW"
];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

Acceder a un elemento de matriz

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Bracket Indexing</h2>

<p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p>

<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>

Cambiar un elemento de matriz

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Bracket Indexing</h2>

<p>Array elements are accessed using their index number:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits[0] = "Kiwi";
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Accede a una gama completa

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

Encuentra la longitud de una matriz

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The length Property</h2>

<p>The length property returns the length of an array:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;
document.getElementById("demo").innerHTML = size;
</script>

</body>
</html>

Recorrer una matriz

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Looping an Array</h2>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;

let text = "<ul>";
for (let i = 0; i < fLen; i++) {
  text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Agregar un elemento a una matriz

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p>The length property provides an easy way to append new elements to an array without using the push() method.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
  fruits[fruits.length] = "Lemon";
  document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>

Agregar "agujeros" indefinidos a una matriz

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p>Adding elements with high indexes can create undefined "holes" in an array.</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon";

let fLen = fruits.length;
let text = "";
for (i = 0; i < fLen; i++) {
  text += fruits[i] + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Matrices explicadas


Métodos de matriz de JavaScript

Agregar un elemento a una matriz

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The push() Method</h2>

<p>The push() method appends a new element to an array:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.push("Kiwi");
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Eliminar el último elemento de una matriz - pop()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The pop() Method</h2>

<p>The pop() method removes the last element from an array.</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.pop();
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Unir todos los elementos de una matriz en una cadena - join()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The join() Method</h2>

<p>The join() method joins array elements into a string.</p>
<p>It this example we have used " * " as a separator between the elements:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
</script>

</body>
</html>

Unir dos matrices - concat()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The concat() Method</h2>

<p>The concat() method merges (concatenates) arrays:</p>

<p id="demo"></p>

<script>
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);

document.getElementById("demo").innerHTML = myChildren;
</script>

</body>
</html>

Unir tres matrices - concat()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The concat() Method</h2>

<p>The concat() method merges (concatenates) arrays:</p>

<p id="demo"></p>

<script>
const array1 = ["Cecilie", "Lone"];
const array2 = ["Emil", "Tobias", "Linus"];
const array3 = ["Robin", "Morgan"];

const myChildren = array1.concat(array2, array3); 

document.getElementById("demo").innerHTML = myChildren;
</script>

</body>
</html>

Agregue un elemento a la posición 2 en una matriz - empalme()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The splice() Method</h2>

<p>The splice() method adds new elements to an array:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;

fruits.splice(2, 0, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Convertir una matriz en una cadena - toString()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1> 
<h2>The toString() Method</h2>

<p>The toString() method returns an array as a comma separated string:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
</script>

</body>
</html>

Agregar nuevos elementos al comienzo de una matriz - unshift()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1> 
<h2>The unshift() Method</h2>

<p>The unshift() method adds new elements to the beginning of an array:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.unshift("Lemon");
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Eliminar el primer elemento de una matriz - shift()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The shift() Method</h2>

<p>The shift() method removes the first element of an array (and "shifts" the other elements to the left):</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.shift();
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Seleccionar elementos de una matriz - rebanada()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The slice() Method</h2>

<p>When the slice() method is given two arguments, it selects array elements from the start argument, and up to (but not included) the end argument:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1,3);
document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus;
</script>

</body>
</html>

Métodos de matriz explicados


Ordenación de matrices de JavaScript

Ordenar una matriz en orden ascendente

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>The sort() method sorts an array alphabetically:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;

fruits.sort();
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Ordenar una matriz en orden descendente

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Sort in Reverse</h2>

<p>The reverse() method reverses the elements in an array.</p>
<p>By combining sort() and reverse() you can sort an array in descending order:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
// Create and display an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;

// First sort the array
fruits.sort();

// Then reverse it:
fruits.reverse();

document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Ordenar una serie de números de forma ascendente

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Sort the array in ascending order:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;  

points.sort(function(a, b){return a - b});
document.getElementById("demo2").innerHTML = points;
</script>

</body>
</html>

Ordenar una serie de números de forma descendente

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Sort the array in descending order:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;

points.sort(function(a, b){return b - a});
document.getElementById("demo2").innerHTML = points;
</script>

</body>
</html>

Ordenar números (alfabéticamente o numéricamente)

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Click the buttons to sort the array alphabetically or numerically.</p>

<button onclick="myFunction1()">Sort Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>

<p id="demo"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;  

function myFunction1() {
  points.sort();
  document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
  points.sort(function(a, b){return a - b});
  document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

Ordenar números de matriz en orden aleatorio

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Click the button (again and again) to sort the array in random order.</p>

<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;  

function myFunction() {
  points.sort(function(){return 0.5 - Math.random()});
  document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

Encuentra el número más bajo en una matriz

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>The lowest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points[0];
</script>

</body>
</html>

Encuentra el número más alto en una matriz

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>The highest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
document.getElementById("demo").innerHTML = points[0];
</script>

</body>
</html>

Encuentre el número más bajo en una matriz usando Math.min()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Array Sort</h1>

<p>The lowest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMin(points);

function myArrayMin(arr) {
  return Math.min.apply(null, arr);
}
</script>

</body>
</html>

Encuentre el número más alto en una matriz usando Math.max()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Array Sort</h1>

<p>The highest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
  return Math.max.apply(null, arr);
}
</script>

</body>
</html>

Usando un método myArrayMin "casero"

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>
<p>The lowest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMin(points);

function myArrayMin(arr) {
  let len = arr.length;
  let min = Infinity;
  while (len--) {
    if (arr[len] < min) {
      min = arr[len];
    }
  }
  return min;
}
</script>

</body>
</html>

Usando un método myArrayMax "casero"

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>
<p>The highest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
  let len = arr.length;
  let max = -Infinity;
  while (len--) {
    if (arr[len] > max) {
      max = arr[len];
    }
  }
  return max;
}
</script>

</body>
</html>

Ordenar objetos por propiedades numéricas

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Sort car objects on age:</p>

<p id="demo"></p>

<script>
const cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}
];

displayCars();

cars.sort(function(a, b){return a.year - b.year});
displayCars();

function displayCars() {
  document.getElementById("demo").innerHTML =
  cars[0].type + " " + cars[0].year + "<br>" +
  cars[1].type + " " + cars[1].year + "<br>" +
  cars[2].type + " " + cars[2].year;
}
</script>

</body>
</html>

Ordenar objetos por propiedades de cadena

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Click the buttons to sort car objects on type.</p>

<button onclick="myFunction()">Sort</button>
<p id="demo"></p>

<script>
const cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}
];

displayCars();

function myFunction() {
  cars.sort(function(a, b){
    let x = a.type.toLowerCase();
    let y = b.type.toLowerCase();
    if (x < y) {return -1;}
    if (x > y) {return 1;}
    return 0;
  });
  displayCars();
}

function displayCars() {
  document.getElementById("demo").innerHTML =
  cars[0].type + " " + cars[0].year + "<br>" +
  cars[1].type + " " + cars[1].year + "<br>" +
  cars[2].type + " " + cars[2].year;
}
</script>

</body>
</html>

Ordenación de matrices


Iteración de matriz de JavaScript

matriz.para cada()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>

<p>Call a function once for each array element:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];

let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;

function myFunction(value, index, array) {
  txt += value + "<br>"; 
}
</script>

</body>
</html>

matriz.mapa()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The map() Method</h2>

<p>Create a new array by performing a function on each array element:</p>

<p id="demo"></p>

<script>
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);

document.getElementById("demo").innerHTML = numbers2;

function myFunction(value, index, array) {
  return value * 2;
}
</script>

</body>
</html>

matriz.filtro()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The filter() Method</h2>

<p>Create a new array from all array elements that passes a test:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

document.getElementById("demo").innerHTML = over18;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

matriz.reducir()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The reduce() Method</h2>

<p>Find the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value, index, array) {
  return total + value;
}
</script>

</body>
</html>

matriz.reduceRight()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The reduceRight() Method</h2>

<p>Find the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value, index, array) {
  return total + value;
}
</script>

</body>
</html>

matriz.cada()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The every() Method</h2>

<p>The every() method checks if all array values pass a test.</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);

document.getElementById("demo").innerHTML = "All over 18 is " + allOver18;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

matriz.algunos()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The some() Method</h2>

<p>The some() method checks if some array values pass a test:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(myFunction);

document.getElementById("demo").innerHTML = "Some over 18 is " + someOver18;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

matriz.indexOf()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The indexOf() Method</h2>

<p id="demo"></p>

<script>
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;

document.getElementById("demo").innerHTML = "Apple is found in position " + position;
</script>

</body>
</html>

Array.lastIndexOf()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The lastIndexOf() Method</h2>

<p id="demo"></p>

<script>
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.lastIndexOf("Apple") + 1;

document.getElementById("demo").innerHTML = "Apple is found in position " + position;
</script>

</body>
</html>

matriz.buscar()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The find() Method</h2>

<p id="demo"></p>

<script>
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);

document.getElementById("demo").innerHTML = "First number over 18 is " + first;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

matriz.findIndex()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The findIndex() Method</h2>

<p id="demo"></p>

<script>
const numbers = [4, 9, 16, 25, 29];

document.getElementById("demo").innerHTML = "First number over 18 has index " + numbers.findIndex(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Iteración de matriz explicada


Conversión de tipo JavaScript

Mostrar el tipo de todos los tipos de variables

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>

<p>The typeof operator returns the type of a variable, object, function or expression:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"'John' is " + typeof "John" + "<br>" +
"3.14 is " + typeof 3.14 + "<br>" +
"NaN is " + typeof NaN + "<br>" +
"false is " + typeof false + "<br>" +
"[1, 2, 3, 4] is " + typeof [1, 2, 3, 4] + "<br>" +
"{name:'John', age:34} is " + typeof {name:'John', age:34} + "<br>" +
"new Date() is " + typeof new Date() + "<br>" +
"function () {} is " + typeof function () {} + "<br>" +
"myCar is " + typeof myCar + "<br>" +
"null is " + typeof null;
</script>

</body>
</html>

Mostrar el constructor de todos los tipos de variables.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Properties</h1>
<h2>The constructor Property</h2>

<p>The constructor property returns the constructor function for a variable or an 
object.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
  "john".constructor + "<br>" +
  (3.14).constructor + "<br>" +
  false.constructor + "<br>" +
  [1,2,3,4].constructor + "<br>" +
  {name:'john', age:34}.constructor + "<br>" +
  new Date().constructor + "<br>" +
  function () {}.constructor;
</script>

</body>
</html>


Convierte un número en una cadena usando String()

<!DOCTYPE html>
<html>
<body>

<h2>The JavaScript String() Method</h2>

<p>The String() method can convert a number to a string.</p>

<p id="demo"></p>

<script>
let x = 123;
document.getElementById("demo").innerHTML =
  String(x) + "<br>" +
  String(123) + "<br>" +
  String(100 + 23);
</script>
</body>
</html>

Convierte un número en una cadena usando toString()

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The toString() method converts a number to a string.</p>

<p id="demo"></p>

<script>
let x = 123;
document.getElementById("demo").innerHTML =
  x.toString() + "<br>" +
   (123).toString() + "<br>" +
   (100 + 23).toString();
</script>

</body>
</html>

Descubra si una variable es una matriz

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p>This &quot;home made&quot; isArray() function returns true when used on an array:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple"];
document.getElementById("demo").innerHTML = isArray(fruits);

function isArray(myArray) {
  return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>

</body>
</html>

Descubra si una variable es una fecha

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Date Object</h2>
<p>This "home made" isDate() function returns true when used on an date:</p>

<p id="demo"></p>

<script>
const myDate = new Date();
document.getElementById("demo").innerHTML = isDate(myDate);

function isDate(myDate) {
  return myDate.constructor.toString().indexOf("Date") > -1;
}
</script>

</body>
</html>

Conversión de tipo explicada


Booleanos de JavaScript

Mostrar el valor de Boolean(10 > 9)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the value of Boolean(10 &gt; 9):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Boolean(10 > 9);
</script>

</body>
</html>

Mostrar el valor de 10 > 9

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the value of 10 &gt; 9:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 10 > 9;
</script>

</body>
</html>

Todo lo que tiene un valor real es verdad.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"100 is " + Boolean(100) + "<br>" +
"3.14 is " + Boolean(3.14) + "<br>" +
"-15 is " + Boolean(-15) + "<br>" +
"Any (not empty) string is " + Boolean("Hello") + "<br>" +
"Even the string 'false' is " + Boolean('false') + "<br>" +
"Any expression (except zero) is " + Boolean(1 + 7 + 3.14);
</script>

</body>
</html>

El valor booleano de cero es falso.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of 0:</p>

<p id="demo"></p>

<script>
let x = 0;
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

El valor booleano de menos cero es falso

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of  -0:</p>

<p id="demo"></p>

<script>
let x = -0;
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

El valor booleano de una cadena vacía es falso

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of "":</p>

<p id="demo"></p>

<script>
let x = "";
document.getElementById("demo").innerHTML = Boolean("");
</script>

</body>
</html>

El valor booleano de indefinido es falso

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of undefined:</p>

<p id="demo"></p>

<script>
let x;
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

El valor booleano de nulo es falso

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of null:</p>

<p id="demo"></p>

<script>
let x = null;
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

El valor booleano de false es false

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of false:</p>

<p id="demo"></p>

<script>
let x = false;
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

El valor booleano de NaN es falso

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of NaN:</p>

<p id="demo"></p>

<script>
let x = 10 / "Hello";
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

Booleanos explicados


Comparaciones de JavaScript

Asigne 5 a x y muestre el valor de (x == 8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The == Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x == 8):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x == 8);
</script>

</body>
</html>

Asigne 5 a x y muestre el valor de (x == 5)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The == Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x == 5):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x == 5);
</script>

</body>
</html>

Asigne 5 a x y muestre el valor de (x === 5)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The === Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x === 5):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x === 5);
</script>

</body>
</html>

Asigne 5 a x y muestre el valor de (x === "5")

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The === Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x === "5").</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x === "5");
</script>

</body>
</html>

Asigne 5 a x y muestre el valor de (x!=8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The != Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x != 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x != 8);
</script>

</body>
</html>

Asigne 5 a x y muestre el valor de (x! == 5)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The !== Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x !== 5):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x !== 5);
</script>

</body>
</html>

Asigne 5 a x y muestre el valor de (x! == "5")

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The !== Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x !== "5"):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x !== "5");
</script>

</body>
</html>

Asigne 5 a x y muestre el valor de (x > 8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &gt; Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &gt; 8).</p>
 
<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x > 8);
</script>

</body>
</html>

Asigne 5 a x y muestre el valor de (x < 8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &lt; Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &lt; 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x < 8);
</script>

</body>
</html>

Asigne 5 a x y muestre el valor de (x >= 8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &gt;= Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &gt;= 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x >= 8);
</script>

</body>
</html>

Asigne 5 a x y muestre el valor de (x <= 8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &lt;= Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &lt;= 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x <= 8);
</script>

</body>
</html>

Comparaciones explicadas


Condicionales de JavaScript

La declaración si

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript if</h2>

<p>Display "Good day!" if the hour is less than 18:00:</p>

<p id="demo">Good Evening!</p>

<script>
if (new Date().getHours() < 18) {
  document.getElementById("demo").innerHTML = "Good day!";
}
</script>

</body>
</html>

La declaración de lo contrario

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript if .. else</h2>

<p>A time-based greeting:</p>

<p id="demo"></p>

<script>
const hour = new Date().getHours(); 
let greeting;

if (hour < 18) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}

document.getElementById("demo").innerHTML = greeting;
</script>

</body>
</html>

La declaración else if

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript if .. else</h2>

<p>A time-based greeting:</p>

<p id="demo"></p>

<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
  greeting = "Good morning";
} else if (time < 20) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>

</body>
</html>

Enlace aleatorio

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.random()</h2>

<p id="demo"></p>

<script>
let text;
if (Math.random() < 0.5) {
  text = "<a href='https://w3schools.com'>Visit W3Schools</a>";
} else {
  text = "<a href='https://wwf.org'>Visit WWF</a>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Declaración de cambio

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript switch</h2>

<p id="demo"></p>

<script>
let day;
switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case  6:
    day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>

</body>
</html>

Condicionales explicados


Bucles de JavaScript

En bucle

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Loop</h2>

<p id="demo"></p>

<script>
let text = "";

for (let i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Bucle de una matriz

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Loop</h2>

<p id="demo"></p>

<script>
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

let text = "";
for (let i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Recorriendo encabezados HTML

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Loop</h2>

<p>Loop from 1 to 6, to make HTML headings.</p>

<div id="demo"></div>

<script>
var x ="", i;
for (i=1; i<=6; i++) {
  x = x + "<h" + i + ">Heading " + i + "</h" + i + ">";
}
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Mientras bucle

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript While Loop</h2>

<p id="demo"></p>

<script>
let text = "";
let i = 0;
while (i < 10) {
  text += "<br>The number is " + i;
  i++;
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Hacer bucle mientras

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Do While Loop</h2>

<p id="demo"></p>

<script>
let text = ""
let i = 0;

do {
  text += "<br>The number is " + i;
  i++;
}
while (i < 10);  

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

romper un bucle

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>break</b> statement.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10; i++) {
  if (i === 3) { break; }
  text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Romper y continuar un bucle

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>continue</b> statement.</p>

<p>A loop which will skip the step where i = 3.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10; i++) {
  if (i === 3) { continue; }
  text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Bucles explicados


Manejo de errores de JavaScript

La declaración try...catch

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Error Handling</h2>

<p>How to use <b>catch</b> to display an error.</p>

<p id="demo"></p>

<script>
try {
  adddlert("Welcome guest!");
}
catch(err) {
  document.getElementById("demo").innerHTML = err.message;
}
</script>

</body>
</html>

La declaración try...catch con un cuadro de confirmación

<!DOCTYPE html>
<html>

<script>
var txt = "";
function message() {
  try {
    adddlert("Welcome guest!");
  }
  catch(err) {
    txt = "There was an error on this page.\n\n";
    txt += "Click OK to continue viewing this page,\n";
    txt += "or Cancel to return to the home page.\n\n";
    if(!confirm(txt)) {
      document.location.href = "https://www.w3schools.com/";
    }
  }
}
</script>

<body>

<h2>JavaScript Error Handling</h2>

<input type="button" value="View message" onclick="message()" />

</body>
</html>

El evento onerror

<!DOCTYPE html>
<html>
<head>
<script>
onerror = handleErr;
var txt = "";
function handleErr(msg, url, l) {
  txt = "There was an error on this page.\n\n";
  txt += "Error: " + msg + "\n";
  txt += "URL: " + url + "\n";
  txt += "Line: " + l + "\n\n";
  txt += "Click OK to continue.\n\n";
  alert(txt);
  return true;
}

function message() {
   adddlert("Welcome guest!");
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>

Errores explicados


Expresiones regulares de JavaScript

Buscar una expresión en una cadena

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Search a string for "w3Schools", and display the position of the match:</p>

<p id="demo"></p>

<script>
let text = "Visit W3Schools!"; 
let n = text.search(/w3Schools/i);
document.getElementById("demo").innerHTML = n;
</script>

</body>
</html>

Busca una expresión y reemplázala

<!DOCTYPE html>
<html>

<body>

<h2>JavaScript String Methods</h2>

<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.replace(/microsoft/i, "W3Schools");
}
</script>

</body>
</html>

Expresiones regulares explicadas


Objetos JavaScript

Creando una variable de JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p id="demo"></p>

<script>
// Create and display a variable:
let person = "John Doe";
document.getElementById("demo").innerHTML = person;
</script>

</body>
</html>

Creando un objeto JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating an object:</p>

<p id="demo"></p>

<script>
let person = {
  firstName : "John",
  lastName  : "Doe",
  age     : 50,
  eyeColor  : "blue"
};

document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName;
</script>

</body>
</html>

Crear un objeto JavaScript (una sola línea)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating a JavaScript Object:</p>

<p id="demo"></p>

<script>
const person = {firstName:"John", lastName:"Doe", age:50,eyeColor:"blue"};

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Crear un objeto JavaScript (varias líneas)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating a JavaScript Object:</p>

<p id="demo"></p>

<script>
const person = {
  firstName: "John",
  lastName: "Doe",
  age: 50,
  eyeColor: "blue"
};

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Crear un objeto JavaScript usando nuevo

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating a JavaScript Object:</p>

<p id="demo"></p>

<script>
const person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue"; 

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Crear objetos JavaScript usando un constructor

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Constructors</h2>

<p id="demo"></p>

<script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");

// Display age
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + "."; 
</script>

</body>
</html>

Crear objetos JavaScript integrados

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var x1 = new Object();   // A new Object object
var x2 = new String();   // A new String object
var x3 = new Number();   // A new Number object
var x4 = new Boolean();  // A new Boolean object
var x5 = new Array();  // A new Array object
var x6 = new RegExp();   // A new RegExp object
var x7 = new Function(); // A new Function object
var x8 = new Date();   // A new Date object

document.getElementById("demo").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>" +
"x8: " + typeof x8 + "<br>";
</script>

<p>There is no need to use String(), Number(), Boolean(), Array(), and RegExp()</p>
<p>Read the JavaScript tutorials.</p>

</body>
</html>

La mejor manera de crear variables de JavaScript

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var x1 = {};
var x2 = "";
var x3 = 0;
var x4 = false;
var x5 = [];
var x6 = /()/;
var x7 = function(){};

document.getElementById("demo").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>";
</script>

</body>
</html>

Los objetos JavaScript son mutables

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>JavaScript objects are mutable.</p>
<p>Any changes to a copy of an object will also change the original object:</p>

<p id="demo"></p>

<script>
const person = {
  firstName: "John",
  lastName: "Doe",
  age:50,
  eyeColor: "blue"
};

const x = person;
x.age = 10;

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Objetos explicados


Propiedades del objeto JavaScript

Accediendo a propiedades usando .property

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>
<p>Access a property with .property:</p>

<p id="demo"></p>

<script>
const person = {
  firstname: "John",
  lastname: "Doe",
  age: 50,
  eyecolor: "blue"
};

document.getElementById("demo").innerHTML = person.firstname + " is " + person.age + " years old.";
</script>

</body>
</html>

Accediendo a propiedades usando [propiedad]

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>
<p>Access a property with ["property"]:</p>

<p id="demo"></p>

<script>
const person = {
  firstname: "John",
  lastname: "Doe",
  age: 50,
  eyecolor: "blue"
};

document.getElementById("demo").innerHTML = person["firstname"] + " is " + person["age"] + " years old.";
</script>

</body>
</html>

Accediendo a propiedades usando for in

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>
<p>Looping object property values:</p>

<p id="demo"></p>

<script>
const person = {
  fname:"John",
  lname:"Doe",
  age:25
}; 

let txt = "";
for (let x in person) {
  txt += person[x] + " ";
}

document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>

Agregar nuevas propiedades a objetos existentes

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>
<p>Add a new property to an existing object:</p>

<p id="demo"></p>

<script>
const person = {
  firstname: "John",
  lastname: "Doe",
  age: 50,
  eyecolor: "blue"
};

person.nationality = "English";
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.nationality + ".";
</script>

</body>
</html>

Eliminar propiedades de objetos

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>
<p>Deleting object properties.</p>

<p id="demo"></p>

<script>
const person = {
  firstname: "John",
  lastname: "Doe",
  age: 50,
  eyecolor: "blue"
};

delete person.age;

document.getElementById("demo").innerHTML =
person.firstname + " is " + person.age + " years old.";
</script>

</body>
</html>

Propiedades del objeto explicadas


Objetos JSON

Accediendo a propiedades usando .property

<!DOCTYPE html>
<html>
<body>

<h2>Access a JavaScript Object</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
</script>

</body>
</html>

Accediendo a propiedades usando [propiedad]

<!DOCTYPE html>
<html>
<body>

<h2>Access a JavaScript Object</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj["name"];
</script>

</body>
</html>

Recorriendo propiedades

<!DOCTYPE html>
<html>
<body>

<h2>Looping Object Properties</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);

let text = "";
for (const x in myObj) {
  text += x + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Recorriendo los valores de las propiedades

<!DOCTYPE html>
<html>
<body>

<h2>Looping JavaScript Object Values</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);

let text = "";
for (const x in myObj) {
  text += myObj[x] + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Acceder a objetos JSON anidados

<!DOCTYPE html>
<html>
<body>

<h2>Access Nested JavaScript Objects</h2>
<p id="demo"></p>

<script>
const myObj = {
  "name":"John",
  "age":30,
  "cars": {
  "car1":"Ford",
  "car2":"BMW",
  "car3":"Fiat"
  }
}
document.getElementById("demo").innerHTML = myObj.cars.car2;
</script>

</body>
</html>

Modificar valores usando la notación de puntos.

<!DOCTYPE html>
<html>
<body>

<p>Modify object values:</p>

<p id="demo"></p>

<script>
let x = "";
let myObj = {
  "name":"John",
  "age":30,
  "cars": {
  "car1":"Ford",
  "car2":"BMW",
  "car3":"Fiat"
  }
}
myObj.cars.car2 = "Mercedes";

for (let i in myObj.cars) {
  x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Modificar valores usando la notación entre corchetes

<!DOCTYPE html>
<html>
<body>

<p>Modify object values using bracket notation:</p>

<p id="demo"></p>

<script>
let x = "";
let myObj = {
  "name":"John",
  "age":30,
  "cars": {
  "car1":"Ford",
  "car2":"BMW",
  "car3":"Fiat"
  }
}
myObj.cars["car2"] = "Mercedes";

for (let i in myObj.cars) {
  x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Eliminar propiedades del objeto

<!DOCTYPE html>
<html>
<body>

<h2>Delete JavaScript Object Properties</h2>

<p id="demo"></p>

<script>
let x = "";
let myObj = {
  "name":"John",
  "age":30,
  "cars": {
  "car1":"Ford",
  "car2":"BMW",
  "car3":"Fiat"
  }
}
delete myObj.cars.car2;

for (let i in myObj.cars) {
  x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Propiedades del objeto JSON explicadas


Matrices JSON

Accediendo a valores de matriz

<!DOCTYPE html>
<html>
<body>

<h2>Access Array Values</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}';
const myObj = JSON.parse(myJSON);

document.getElementById("demo").innerHTML = myObj.cars[0];
</script>

</body>
</html>

Recorriendo una matriz usando for-in

<!DOCTYPE html>
<html>
<body>

<h2>Looping an Array</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}';
const myObj = JSON.parse(myJSON);

let text = "";
for (let i in myObj.cars) {
  text += myObj.cars[i] + ", ";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Recorriendo una matriz usando for

<!DOCTYPE html>
<html>
<body>

<h2>Looping an Array</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}';
const myObj = JSON.parse(myJSON);

let text = "";
for (let i = 0; i < myObj.cars.length; i++) {
  text += myObj.cars[i] + ", ";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Acceda a matrices JSON anidadas

<!DOCTYPE html>
<html>
<body>

<p>Looping through arrays inside arrays.</p>
<p id="demo"></p>

<script>
let x = "";
const myObj = {
  "name":"John",
  "age":30,
  "cars": [
    {"name":"Ford", "models":["Fiesta", "Focus", "Mustang"]},
    {"name":"BMW", "models":["320", "X3", "X5"]},
    {"name":"Fiat", "models":["500", "Panda"] }
  ]
}

for (let i in myObj.cars) {
  x += "<h2>" + myObj.cars[i].name + "</h2>";
  for (let j in myObj.cars[i].models) {
    x += myObj.cars[i].models[j] + "<br>";
  }
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Modificar valores de matriz

<!DOCTYPE html>
<html>
<body>

<p>Modify an array value of an object.</p>
<p id="demo"></p>

<script>
let x = "";
const myObj = {
  "name":"John",
  "age":30,
  "cars":[ "Ford", "BMW", "Fiat" ]
};

myObj.cars[1] = "Mercedes";

for (let i in myObj.cars) {
  x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Eliminar elementos de la matriz

<!DOCTYPE html>
<html>
<body>

<p>Delete array properties:</p>
<p id="demo"></p>

<script>
let x = "";
const myObj = {
  "name":"John",
  "age":30,
  "cars": ["Ford","BMW","Fiat"]
}

delete myObj.cars[1];

for (let i in myObj.cars) {
  x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Matrices JSON explicadas


Análisis JSON

Usar análisis JSON

<!DOCTYPE html>
<html>
<body>

<h2>Creating an Object from a JSON String</h2>

<p id="demo"></p>

<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>

</body>
</html>

Usando el análisis JSON en un ejemplo de AJAX

<!DOCTYPE html>
<html>
<body>

<h2>Fetch a JSON file with XMLHttpRequest</h2>
<p id="demo"></p>

<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "json_demo.txt");
xmlhttp.send();
</script>

</body>
</html>

Usando análisis JSON en una matriz

<!DOCTYPE html>
<html>
<body>

<h2>Fetch a JSON file with XMLHttpRequest</h2>
<p>Content written as an JSON array will be converted into a JavaScript array.</p>
<p id="demo"></p>

<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myArr = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myArr[0];
}
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();
</script>

</body>
</html>

Analizando fechas

<!DOCTYPE html>
<html>
<body>

<h2>Convert a string into a date object.</h2>
<p id="demo"></p>

<script>
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth; 
</script>

</body>
</html>

Analizar fechas usando la función reviver

<!DOCTYPE html>
<html>
<body>

<h2>Convert a string into a date object.</h2>

<p id="demo"></p>

<script>
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text, function (key, value) {
  if (key == "birth") {
    return new Date(value);
  } else {
    return value;
  }
});
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth; 
</script>

</body>
</html>

Funciones de análisis

<!DOCTYPE html>
<html>
<body>

<h2>Convert a string into a function.</h2>
<p id="demo"></p>

<script>
const text = '{"name":"John", "age":"function() {return 30;}", "city":"New York"}';
const obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age(); 
</script>

</body>
</html>

Análisis JSON explicado


Cadena JSON

Utilice cadena JSON

<!DOCTYPE html>
<html>
<body>

<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>

<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>

Usando JSON stringify en una matriz

<!DOCTYPE html>
<html>
<body>

<h2>Create a JSON string from a JavaScript array.</h2>
<p id="demo"></p>

<script>
const arr = ["John", "Peter", "Sally", "Jane"];
const myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>

Stringificar fechas

<!DOCTYPE html>
<html>
<body>

<h2>JSON.stringify() converts date objects into strings.</h2>
<p id="demo"></p>

<script>
const obj = {name: "John", today: new Date(), city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>

Funciones de cadena

<!DOCTYPE html>
<html>
<body>

<h2>JSON.stringify() will remove any functions from an object.</h2>
<p id="demo"></p>

<script>
const obj = {name: "John", age: function () {return 30;}, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>

Stringificar funciones usando el método toString()

<!DOCTYPE html>
<html>
<body>

<h2>JSON.stringify() will remove any functions from an object.</h2>
<p>Convert functions into strings to keep them in the JSON object.</p>

<p id="demo"></p>

<script>
const obj = {name: "John", age: function () {return 30;}, city: "New York"};
obj.age = obj.age.toString();
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>

JSON Stringify explicado


JSONPHP

Obtener JSON de un archivo php

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p id="demo"></p>

<script>
const xmlhttp = new XMLHttpRequest();

xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "demo_file.php");
xmlhttp.send();
</script>

</body>
</html>

Obtener matriz JSON de php

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p>Convert the data into a JavaScript array:</p>
<p id="demo"></p>

<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj[2];
}
xmlhttp.open("GET", "demo_file_array.php");
xmlhttp.send();
</script>

</body>
</html>

Obtener JSON de una base de datos

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p>The JSON received from the PHP file:</p>

<p id="demo"></p>

<script>
const dbParam = JSON.stringify({"limit":10});

const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  document.getElementById("demo").innerHTML = this.responseText;
}
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam);
xmlhttp.send();
</script>

</body>
</html>

Recorrer el resultado desde una base de datos

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p id="demo"></p>

<script>
const obj = { "limit":10 };
const dbParam = JSON.stringify(obj);
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  myObj = JSON.parse(this.responseText);
  let text = ""
  for (let x in myObj) {
    text += myObj[x].name + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam);
xmlhttp.send();
</script>

<p>Try changing the "limit" property from 10 to 5.</p>

</body>
</html>

Enviar JSON usando el método POST

<!DOCTYPE html>
<html>
<body>

<h2>Use HTTP POST to Get JSON Data from a PHP Server</h2>

<p id="demo"></p>

<script>
const dbParam = JSON.stringify({"limit":10});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  myObj = JSON.parse(this.responseText);
  let text = "";
  for (let x in myObj) {
    text += myObj[x].name + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_db_post.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
</script>

<p>Try changing the "limit" property from 10 to 5.</p>

</body>
</html>

JSON PHP explicado


HTML JSON

Haga una tabla HTML basada en datos JSON

<!DOCTYPE html>
<html>
<body>

<h2>Make a table based on JSON data.</h2>

<p id="demo"></p>

<script>
const dbParam = JSON.stringify({table:"customers",limit:20});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  let text = "<table border='1'>"
  for (let x in myObj) {
    text += "<tr><td>" + myObj[x].name + "</td></tr>";
  }
  text += "</table>"    
  document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_html_table.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
</script>

</body>
</html>

Hacer una tabla HTML dinámica

<!DOCTYPE html>
<html>
<body>

<h2>Make a table based on the value of a drop down menu.</h2>

<select id="myselect" onchange="change_myselect(this.value)">
  <option value="">Choose an option:</option>
  <option value="customers">Customers</option>
  <option value="products">Products</option>
  <option value="suppliers">Suppliers</option>
</select>

<p id="demo"></p>

<script>
function change_myselect(sel) {
  const dbParam = JSON.stringify({table:sel,limit:20});
  const xmlhttp = new XMLHttpRequest();
  xmlhttp.onload = function() {
    myObj = JSON.parse(this.responseText);
    text = "<table border='1'>"
    for (x in myObj) {
      text += "<tr><td>" + myObj[x].name + "</td></tr>";
    }
    text += "</table>"    
    document.getElementById("demo").innerHTML = text;
  }
  xmlhttp.open("POST", "json_demo_html_table.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("x=" + dbParam);
}
</script>

</body>
</html>

Haga una lista desplegable HTML basada en datos JSON

<!DOCTYPE html>
<html>
<body>

<h2>Make a drop down list based on JSON data.</h2>
<p id="demo"></p>

<script>
const dbParam = JSON.stringify({table:"customers",limit:20});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  let text = "<select>"
  for (let x in myObj) {
    text += "<option>" + myObj[x].name + "</option>";
  }
  text += "</select>"
  document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_html_table.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
</script>

</body>
</html>

HTML JSON explicado


JSON JSONP

Ejemplo JSONP sencillo

<!DOCTYPE html>
<html>
<body>

<h2>Request JSON using the script tag</h2>
<p>The PHP file returns a call to a function that will handle the JSON data.</p>
<p id="demo"></p>

<script>
function myFunc(myObj) {
  document.getElementById("demo").innerHTML = myObj.name;
}
</script>

<script src="demo_jsonp.php"></script>

</body>
</html>

Crear una etiqueta de secuencia de comandos dinámica

<!DOCTYPE html>
<html>

<body>

<h2>Click the Button.</h2>
<p>A script tag with a src attribute is created and placed in the document.</p>
<p>The PHP file returns a call to a function with the JSON object as a parameter.</p>

<button onclick="clickButton()">Click me!</button>

<p id="demo"></p>

<script>
function clickButton() {
  let s = document.createElement("script");
  s.src = "demo_jsonp.php";
  document.body.appendChild(s);
}

function myFunc(myObj) {
  document.getElementById("demo").innerHTML = myObj.name;
}
</script>

</body>
</html>

Ejemplo JSONP con resultado dinámico

<!DOCTYPE html>
<html>
<body>

<p>A script tag with a src attribute is created and placed in the document.</p>
<p>The PHP file returns a call to a function with an object as a parameter.</p>
<p id="demo"></p>

<p>Try changing the table property from "customers" to "products".</p>

<script>
const obj = { table: "customers", limit: 10 };
let s = document.createElement("script");
s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj);
document.body.appendChild(s);

function myFunc(myObj) {
  let txt = "";
  for (let x in myObj) {
    txt += myObj[x].name + "<br>";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Ejemplo JSONP con una función de devolución de llamada

<!DOCTYPE html>
<html>
<body>

<h2>Request With a Callback Function</h2>
<p>The PHP file returns a call to the function you send as a callback.</p>
<p id="demo"></p>

<script>
let s = document.createElement("script");
s.src = "demo_jsonp2.php?callback=myDisplayFunction";
document.body.appendChild(s);

function myDisplayFunction(myObj) {
  document.getElementById("demo").innerHTML = myObj.name;
}
</script>

</body>
</html>

JSON JSONP explicado