ECMAScript 2015 fue la segunda revisión importante de JavaScript.
ECMAScript 2015 también se conoce como ES6 y ECMAScript 6.
Este capítulo describe las características más importantes de ES6.
La palabra clave let
La palabra clave constante
Funciones de flecha
El operador
Para/de
Objetos del mapa
Establecer objetos
Clases
Promesas
Símbolo
Parámetros predeterminados
Parámetro de descanso de función
Cadena.incluye()
Cadena.startsWith()
Cadena.endsWith()
matriz.de()
Teclas de matriz()
búsqueda de matriz()
matriz findIndex()
Nuevos métodos matemáticos
Nuevas propiedades numéricas
Nuevos métodos numéricos
Nuevos métodos globales
Entradas de objetos
Módulos JavaScript
Safari 10 y Edge 14 fueron los primeros navegadores totalmente compatibles con ES6:
Chrome 58 | Edge 14 | Firefox 54 | Safari 10 | Opera 55 |
Jan 2017 | Aug 2016 | Mar 2017 | Jul 2016 | Aug 2018 |
La palabra clave let
le permite declarar una variable con alcance del bloque.
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>Redeclaring a Variable Using let</h2>
<p id="demo"></p>
<script>
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Lea más sobre let
en el capítulo: JavaScript Let.
La palabra clave const
le permite declarar una constante (una Variable JavaScript con un valor constante).
Las constantes son similares a las variables let, excepto que el valor no se puede cambiar.
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>Declaring a Variable Using const</h2>
<p id="demo"></p>
<script>
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Lea más sobre const
en el capítulo: JavaScript Const.
Las funciones de flecha permiten una sintaxis corta para escribir expresiones de funciones.
No necesita la palabra clave función
, la palabra clave return
y la llaves.
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Functions</h2>
<p>With arrow functions, you don't have to type the function keyword, the return keyword, and the curly brackets.</p>
<p>Arrow functions are not supported in IE11 or earlier.</p>
<p id="demo"></p>
<script>
const x = (x, y) => x * y;
document.getElementById("demo").innerHTML = x(5, 5);
</script>
</body>
</html>
Las funciones de flecha no tienen su propio this
. No son muy adecuados para definir métodos de objetos.
Las funciones de flecha no están elevadas. Deben definirse antes de ser utilizados.
Usando const
es más seguro que usar var
, porque una expresión de función es siempre un valor constante.
Solo puede omitir la palabra clave return
y las llaves si la función es una declaración única. Por este motivo, puede ser una buena costumbre conservarlos siempre:
const x = (x, y) => { return x * y };
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Functions</h2>
<p>Arrow functions are not supported in IE11 or earlier.</p>
<p id="demo"></p>
<script>
const x = (x, y) => { return x * y };
document.getElementById("demo").innerHTML = x(5, 5);
</script>
</body>
</html>
Obtenga más información sobre las funciones de flecha en el capítulo: Función de flecha de JavaScript.
El operador ... expande un iterable (como una matriz) en más elementos:
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];
const year = [...q1, ...q2, ...q3, ...q4];
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Operators</h1>
<h2>The ... Operator</h2>
<p>The "spread" operator spreads elements of iterable objects:</p>
<p id="demo"></p>
<script>
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];
const year = [...q1, ...q2, ...q3, ...q4];
document.getElementById("demo").innerHTML = year;
</script>
</body>
</html>
El operador ... se puede utilizar para expandir un iterable en más argumentos para llamadas a funciones:
const numbers = [23,55,21,87,56];
let maxValue = Math.max(...numbers);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Operators</h1>
<h2>The ... Operator</h2>
<p>The "Spread" operator can be used to expand an iterable into more arguments for function calls:</p>
<p id="demo"></p>
<script>
const numbers = [23,55,21,87,56];
let maxValue = Math.max(...numbers);
document.getElementById("demo").innerHTML = maxValue;
</script>
</body>
</html>
La instrucción for/of
de JavaScript se repite en bucle. a través de los valores de un objeto iterable.
for/of
te permite recorrer estructuras de datos que son iterables, como matrices, cadenas, mapas, listas de nodos y más.
El bucle for/of
tiene la siguiente sintaxis:
for (variable of iterable) {
// code block to be executed
}
variable: para cada iteración, el valor de la siguiente propiedad es asignado a la variable. Variable se puede declarar con const
, let
o var
.
iterable: un objeto que tiene propiedades iterables.
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + " ";
}
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of any iterable object:</p>
<p id="demo"></p>
<script>
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + " ";
}
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of an iterable object.</p>
<p id="demo"></p>
<script>
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Obtenga más información en el capítulo: Bucle JavaScript For/In/Of.
Poder utilizar un Objeto como clave es una característica importante del Mapa.
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Creating a Map from an Array:</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
document.getElementById("demo").innerHTML = fruits.get("apples");
</script>
</body>
</html>
Obtenga más información sobre los objetos Map y la diferencia entre un Map y un Array en el capítulo: Mapas JavaScript.
// Create a Set
const letters = new Set();
// Add some values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Sets</h2>
<p>Add values to a Set:</p>
<p id="demo"></p>
<script>
// Create a Set
const letters = new Set();
// Add Values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
// Display set.size
document.getElementById("demo").innerHTML = letters.size;
</script>
</body>
</html>
Obtenga más información sobre los objetos Set en el capítulo: Conjuntos de JavaScript.
Las clases de JavaScript son plantillas para objetos de JavaScript.
Utilice la palabra clave class
para crear una clase.
Agregue siempre un método llamado constructor()
:
class ClassName {
constructor() { ... }
}
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
El ejemplo anterior crea una clase denominada "Coche".
La clase tiene dos propiedades iniciales: "nombre" y "año".
Una clase de JavaScript no es un objeto.
Es una plantilla para objetos JavaScript.
Cuando tienes una clase, puedes usar la clase para crear objetos:
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Classes</h1>
<p>Creating two car objects from a car class:</p>
<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
document.getElementById("demo").innerHTML =
myCar1.name + " " + myCar2.name;
</script>
</body>
</html>
Obtenga más información sobre las clases en el capítulo: Clases de JavaScript.
Una Promesa es un objeto JavaScript que vincula "Producir código" y "Consumir código".
"Producir código" puede llevar algún tiempo y "Consumir código" debe esperar el resultado.
const myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// "Consuming Code" (Must wait for a fulfilled Promise).
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
const myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Promise</h2>
<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
<h1 id="demo"></h1>
<script>
const myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function(){ myResolve("I love You !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
</script>
</body>
</html>
Obtenga más información sobre las Promesas en el capítulo: Promesas de JavaScript.
Un símbolo de JavaScript es un tipo de datos primitivo como Número, Cadena o Booleano.
Representa un identificador único "oculto" al que ningún otro código puede acceder accidentalmente.
Por ejemplo, si diferentes codificadores quieren agregar una propiedad person.id a un objeto persona que pertenece a un código de terceros, podrían mezclar los valores de los demás.
Usar Symbol() para crear identificadores únicos resuelve este problema:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
let id = Symbol('id');
person[id] = 140353;
// Now person[id] = 140353
// but person.id is still undefined
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>Using JavaScript Symbol()</h2>
<p id="demo"></p>
<script>
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
let id = Symbol('id');
person[id] = 140353;
document.getElementById("demo").innerHTML = person[id] + " " + person.id;
</script>
</body>
</html>
Los símbolos son siempre únicos.
Si crea dos símbolos con la misma descripción, tendrán valores diferentes:
Symbol("id") == Symbol("id"); // false
ES6 permite que los parámetros de función tengan valores predeterminados.
function myFunction(x, y = 10) { // y is 10 if not passed or undefined return x + y;
}
myFunction(5); // will return 15
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>Default Parameter Values</h2>
<p>If y is not passed or undefined, then y = 10:</p>
<p id="demo"></p>
<script>
function myFunction(x, y = 10) {
return x + y;
}
document.getElementById("demo").innerHTML = myFunction(5);
</script>
</body>
</html>
El parámetro rest (...) permite que una función trate un número indefinido de argumentos como una matriz:
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>The Rest Parameter</h2>
<p>The rest parameter (...) allows a function to treat an indefinite number of arguments as an array:</p>
<p id="demo"></p>
<script>
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
El método includes()
devuelve true
si una cadena contiene un valor específico, de lo contrario falso
:
let text = "Hello world, welcome to the universe.";
text.includes("world") // Returns true
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The includes() Method</h2>
<p>Check if a string includes "world":</p>
<p id="demo"></p>
<p>The includes() method is not supported in Internet Explorer.</p>
<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.includes("world");
</script>
</body>
</html>
El método startsWith()
devuelve true
si una cadena comienza con un valor específico, de lo contrario false
:
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello") // Returns true
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The startsWith() Method</h2>
<p>Check if a string starts with "Hello":</p>
<p id="demo"></p>
<p>The startsWith() method is not supported in Internet Explorer.</p>
<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("Hello");
</script>
</body>
</html>
El método endsWith()
devuelve true
si una cadena termina con un valor específico, de lo contrario false
:
var text = "John Doe";
text.endsWith("Doe") // Returns true
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>Check if a string ends with "Doe":</p>
<p id="demo"></p>
<p>The endsWith() method is not supported in Internet Explorer.</p>
<script>
let text = "John Doe";
document.getElementById("demo").innerHTML = text.endsWith("Doe");
</script>
</body>
</html>
El método Array.from()
devuelve un objeto Array de cualquier objeto con una longitud propiedad o cualquier objeto iterable.
Cree una matriz a partir de una cadena:
Array.from("ABCDEFG") // Returns [A,B,C,D,E,F,G]
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The from() Method</h2>
<p>Return an array object from any object with a length property or any iterable object.</p>
<p id="demo"></p>
<script>
const myArr = Array.from("ABCDEFG");
document.getElementById("demo").innerHTML = myArr;
</script>
<p>The Array.from() method is not supported in Internet Explorer.</p>
</body>
</html>
El método keys()
devuelve un objeto Array Iterator con las claves de una matriz.
Cree un objeto Array Iterator, que contenga las claves de la matriz:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();
let text = "";
for (let x of keys) {
text += x + "<br>";
}
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The keys() Method</h2>
<p>Return an Array Iterator object with the keys of the array:</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();
let text = "";
for (let x of keys) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
<p>Array.keys() is not supported in Internet Explorer.</p>
</body>
</html>
El método find()
devuelve el valor del primer elemento de la matriz que pasa un función de prueba.
Este ejemplo encuentra (devuelve el valor de) el primer elemento que es más grande de 18:
const numbers = [4, 9, 16, 25, 29];
let first =
numbers.find(myFunction);
function myFunction(value, index, array) {
return
value > 18;
}
Pruébelo usted mismo →
<!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>
Tenga en cuenta que la función toma 3 argumentos:
El valor del artículo
El índice de artículos
La matriz en sí
El método findIndex()
devuelve el índice del primer elemento de la matriz que pasa una función de prueba.
Este ejemplo encuentra el índice del primer elemento mayor que 18:
const numbers = [4, 9, 16, 25, 29];
let first =
numbers.findIndex(myFunction);
function myFunction(value, index, array) {
return
value > 18;
}
Pruébelo usted mismo →
<!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>
Tenga en cuenta que la función toma 3 argumentos:
El valor del artículo
El índice de artículos
La matriz en sí
ES6 agregó los siguientes métodos al objeto Math:
Math.trunc()
Math.sign()
Math.cbrt()
Math.log2()
Math.log10()
Math.trunc(x)
devuelve la parte entera de x:
Math.trunc(4.9); // returns 4
Math.trunc(4.7); // returns 4
Math.trunc(4.4); // returns 4
Math.trunc(4.2); // returns 4
Math.trunc(-4.2); // returns -4
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.trunc()</h2>
<p>Math.trunc(x) returns the integer part of x:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.trunc(4.7);
</script>
</body>
</html>
Math.sign(x)
devuelve si x es negativo, nulo o positivo:
Math.sign(-4); // returns -1
Math.sign(0); // returns 0
Math.sign(4); // returns 1
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.sign()</h2>
<p>Math.sign(x) returns if x is negative, null or positive:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.sign(4);
</script>
</body>
</html>
Math.cbrt(x)
devuelve la raíz cúbica de x:
Math.cbrt(8); // returns 2
Math.cbrt(64); // returns 4
Math.cbrt(125); // returns 5
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.cbrt()</h2>
<p>Math.cbrt(x) returns the cube root of x:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.cbrt(8);
</script>
</body>
</html>
Math.log2(x)
devuelve el logaritmo en base 2 de x:
Math.log2(2); // returns 1
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.log2()</h2>
<p>Math.log2() returns the base 2 logarithm of a number.</p>
<p>How many times must we multiply 2 to get 8?</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.log2(8);
</script>
</body>
</html>
Math.log10(x)
devuelve el logaritmo en base 10 de x:
Math.log10(10); // returns 1
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.log10()</h2>
<p>Math.log10() returns the base 10 logarithm of a number.</p>
<p>How many times must we multiply 10 to get 1000?</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.log10(1000);
</script>
</body>
</html>
ES6 agregó las siguientes propiedades al objeto Número:
let x = Number.EPSILON;
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>Number Object Properties</h2>
<p>EPSILON</p>
<p id="demo"></p>
<script>
let x = Number.EPSILON;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
let x = Number.MIN_SAFE_INTEGER;
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>Number Object Properties</h2>
<p>MIN_SAFE_INTEGER</p>
<p id="demo"></p>
<script>
let x = Number.MIN_SAFE_INTEGER;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
let x = Number.MAX_SAFE_INTEGER;
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>Number Object Properties</h2>
<p>MAX_SAFE_INTEGER</p>
<p id="demo"></p>
<script>
let x = Number.MAX_SAFE_INTEGER;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
ES6 agregó 2 nuevos métodos al objeto Número:
Number.isInteger()
Number.isSafeInteger()
El método Number.isInteger()
devuelve true
si el argumento es un número entero.
Number.isInteger(10); // returns true
Number.isInteger(10.5); // returns false
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Numbers</h1>
<h2>The isInteger() Method</h2>
<p>The isInteger() method returns true if the argument is an integer.</p>
<p>Otherwise it returns false.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
Number.isInteger(10) + "<br>" + Number.isInteger(10.5);
</script>
</body>
</html>
Un número entero seguro es un número entero que se puede representar exactamente como un número de doble precisión.
El método Number.isSafeInteger()
devuelve true
si el argumento es un entero seguro.
Number.isSafeInteger(10); // returns true
Number.isSafeInteger(12345678901234567890); // returns false
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Numbers</h1>
<h2>The isSafeInteger() Method</h2>
<p>The isSafeInteger() method returns true if the argument is a safe integer.</p>
<p>Otherwise it returns false.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
Number.isSafeInteger(10) + "<br>" + Number.isSafeInteger(12345678901234567890);
</script>
</body>
</html>
Los enteros seguros son todos los números enteros desde -(253 - 1) hasta +(253 - 1).
Esto es seguro: 9007199254740991. Esto no es seguro: 9007199254740992.
ES6 agregó 2 nuevos métodos numéricos globales:
isFinite()
El método global isFinite()
devuelve false
si el argumento es Infinito
o NaN
.
De lo contrario, devuelve true
:
isFinite(10/0); // returns false
isFinite(10/1); // returns true
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Numbers</h1>
<h2>The isFinite() Method</h2>
<p>The isFinite() method returns false if the argument is Infinity or NaN.</p>
<p>Otherwise it returns true.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
isFinite(10 / 0) + "<br>" + isFinite(10 / 1);
</script>
</body>
</html>
El método global isNaN()
devuelve true
si el argumento es NaN
. De lo contrario, devuelve false
:
isNaN("Hello"); // returns true
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Numbers</h1>
<h2>The isNaN() Method</h2>
<p>The isNan() method returns true if the argument is NaN. Otherwise it returns false.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
isNaN("Hello") + "<br>" + isNaN("10");
</script>
</body>
</html>
Cree un iterador de matriz y luego repita los pares clave/valor:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const f = fruits.entries();
for (let x of f) {
document.getElementById("demo").innerHTML += x;
}
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The entries() method</h2>
<p>entries() returns an Array Iterator object with key/value pairs:</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const f = fruits.entries();
for (let x of f) {
document.getElementById("demo").innerHTML += x + "<br>";
}
</script>
<p>The entries() method is not supported in Internet Explorer 11 (or earlier).</p>
</body>
</html>
El método entries()
devuelve un objeto Array Iterator con pares clave/valor:
[0, "Plátano"]
[1, "Naranja"]
[2, "Manzana"]
[3, "Mango"]
El método entries()
no cambia la matriz original.
Los módulos se importan de dos formas diferentes:
Importe exportaciones con nombre desde el archivo person.js:
import { name, age } from "./person.js";
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Modules</h1>
<p id="demo"></p>
<script type="module">
import { name, age } from "./person.js";
let text = "My name is " + name + ", I am " + age + ".";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Importe una exportación predeterminada desde el archivo message.js:
import message from "./message.js";
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Modules</h1>
<p id="demo"></p>
<script type="module">
import message from "./message.js";
document.getElementById("demo").innerHTML = message();
</script>
</body>
</html>
Obtenga más información sobre los módulos en: Módulos de JavaScript.