JavaScript ES5
ECMAScript 2009, también conocido como ES5, fue la primera revisión importante de JavaScript.
Este capítulo describe las funciones más importantes de ES5.
Características de ES5
- "uso estricto"
- Cadena [ número ] acceso
- Cadenas multilínea
- Cadena.trim()
- Array.isArray()
- matriz para cada uno ()
- mapa de matriz ()
- filtro de matriz ()
- reducción de matriz ()
- Matriz reduceRight()
- Arreglo cada ()
- Arreglar algunos ()
- índice de matriz de ()
- Array lastIndexOf()
- JSON.parse()
- JSON.stringify()
- Fecha.ahora()
- Fecha paraISOString()
- Fecha para JSON()
- captadores y setters de propiedades
- Palabras reservadas como nombres de propiedad
- Métodos de objeto
- Objeto definirPropiedad()
- Función.bind()
- comas finales
Compatibilidad con navegador
ES5
es totalmente compatible con todos los navegadores modernos:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9.0 | Yes | Yes | Yes | Yes |
La Directiva de "uso estricto"
"use strict"
define que el código JavaScript debe ejecutarse en "modo estricto".
Con el modo estricto puede, por ejemplo, no usar variables no declaradas.
Puede usar el modo estricto en todos sus programas. Le ayuda a escribir un código más limpio, como evitar que use variables no declaradas.
"use strict"
es solo una expresión de cadena. Los navegadores antiguos no arrojarán un error si no lo entienden.
Obtenga más información en el modo estricto de JS .
Acceso a propiedades en cadenas
El charAt()
método devuelve el carácter en un índice especificado (posición) en una cadena:
Ejemplo
var str = "HELLO WORLD";
str.charAt(0); // returns H
ES5 permite el acceso a la propiedad en cadenas:
Ejemplo
var str = "HELLO WORLD";
str[0]; // returns H
El acceso a la propiedad en la cadena puede ser un poco impredecible.
Obtenga más información en Métodos de cadena JS .
Cadenas sobre varias líneas
ES5 permite literales de cadena en varias líneas si se escapa con una barra invertida:Ejemplo
"Hello \
Dolly!";
Es posible que el método \ no tenga soporte universal.
Los navegadores más antiguos pueden tratar los espacios alrededor de la barra invertida de manera diferente.
Algunos navegadores antiguos no permiten espacios detrás del carácter \.
Una forma más segura de dividir un literal de cadena es usar la suma de cadenas:
Ejemplo
"Hello " +
"Dolly!";
Palabras reservadas como nombres de propiedad
ES5 permite palabras reservadas como nombres de propiedad:
Ejemplo de objeto
var obj = {name: "John", new: "yes"}
Recorte de cadena ()
El trim()
método elimina los espacios en blanco de ambos lados de una cadena.
Ejemplo
var str = " Hello World! ";
alert(str.trim());
Obtenga más información en Métodos de cadena JS .
Array.isArray()
El isArray()
método verifica si un objeto es una matriz.
Ejemplo
function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = document.getElementById("demo");
x.innerHTML = Array.isArray(fruits);
}
Obtenga más información en Matrices JS .
matriz para cada uno ()
El forEach()
método llama a una función una vez para cada elemento de la matriz.
Ejemplo
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value) {
txt = txt + value + "<br>";
}
Obtenga más información en Métodos de iteración de matriz JS .
mapa de matriz ()
Este ejemplo multiplica cada valor de matriz por 2:
Ejemplo
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value) {
return value * 2;
}
Obtenga más información en Métodos de iteración de matriz JS .
filtro de matriz ()
Este ejemplo crea una nueva matriz a partir de elementos con un valor superior a 18:
Ejemplo
var numbers = [45, 4, 9, 16, 25];
var over18 =
numbers.filter(myFunction);
function myFunction(value) {
return value > 18;
}
Obtenga más información en Métodos de iteración de matriz JS .
reducción de matriz ()
Este ejemplo encuentra la suma de todos los números en una matriz:
Ejemplo
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);
function myFunction(total, value) {
return total + value;
}
Obtenga más información en Métodos de iteración de matriz JS .
Matriz reduceRight()
Este ejemplo también encuentra la suma de todos los números en una matriz:
Ejemplo
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);
function myFunction(total, value) {
return total + value;
}
Obtenga más información en Métodos de iteración de matriz JS .
Arreglo cada ()
Este ejemplo comprueba si todos los valores son mayores de 18:
Ejemplo
var numbers = [45, 4, 9, 16, 25];
var allOver18 =
numbers.every(myFunction);
function myFunction(value) {
return
value > 18;
}
Obtenga más información en Métodos de iteración de matriz JS .
Arreglar algunos ()
Este ejemplo comprueba si algunos valores son mayores de 18:
Ejemplo
var numbers = [45, 4, 9, 16, 25];
var allOver18 =
numbers.some(myFunction);
function myFunction(value) {
return
value > 18;
}
Obtenga más información en Métodos de iteración de matriz JS .
índice de matriz de ()
Busca en una matriz el valor de un elemento y devuelve su posición.
Ejemplo
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
Obtenga más información en Métodos de iteración de matriz JS .
Array lastIndexOf()
lastIndexOf()
es lo mismo que indexOf()
, pero busca desde el final de la matriz.
Ejemplo
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");
Obtenga más información en Métodos de iteración de matriz JS .
JSON.parse()
Un uso común de JSON es recibir datos de un servidor web.
Imagina que recibiste esta cadena de texto de un servidor web:
'{"name":"John", "age":30, "city":"New York"}'
La función JavaScript JSON.parse()
se utiliza para convertir el texto en un objeto JavaScript:
var obj = JSON.parse('{"name":"John", "age":30, "city":"New
York"}');
Lea más en nuestro Tutorial JSON .
JSON.stringify()
Un uso común de JSON es enviar datos a un servidor web.
Al enviar datos a un servidor web, los datos deben ser una cadena.
Imagina que tenemos este objeto en JavaScript:
var obj = {name:"John", age:30, city:"New York"};
Utilice la función de JavaScript JSON.stringify()
para convertirlo en una cadena.
var myJSON = JSON.stringify(obj);
El resultado será una cadena siguiendo la notación JSON.
myJSON ahora es una cadena y está lista para ser enviada a un servidor:
Ejemplo
var obj = {name:"John", age:30, city:"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Lea más en nuestro Tutorial JSON .
Fecha.ahora()
Date.now()
returns the number of milliseconds since zero date (January 1.
1970 00:00:00 UTC).
Example
var timInMSs = Date.now();
Date.now()
returns the same as getTime() performed on a Date
object.
Learn more in JS Dates.
Date toISOString()
The toISOString()
method converts a Date object to a string, using the ISO standard format:
Example
const d = new Date();
document.getElementById("demo").innerHTML = d.toISOString();
Date toJSON()
toJSON()
converts a Date object into a string, formatted as a JSON date.
JSON dates have the same format as the ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ:
Example
d = new Date();
document.getElementById("demo").innerHTML = d.toJSON();
Property Getters and Setters
ES5 lets you define object methods with a syntax that looks like getting or setting a property.
This example creates a getter for a property called fullName:
Example
// Create an object:
var person = {
firstName:
"John",
lastName : "Doe",
get
fullName() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the
object using a getter:
document.getElementById("demo").innerHTML =
person.fullName;
This example creates a setter and a getter for the language property:
Example
var person = {
firstName: "John",
lastName : "Doe",
language : "NO",
get lang() {
return this.language;
},
set lang(value) {
this.language = value;
}
};
// Set an object
property using a setter:
person.lang = "en";
// Display data from the
object using a getter:
document.getElementById("demo").innerHTML =
person.lang;
This example uses a setter to secure upper case updates of language:
Example
var person = {
firstName: "John",
lastName : "Doe",
language : "NO",
set lang(value) {
this.language = value.toUpperCase();
}
};
// Set an object
property using a setter:
person.lang = "en";
// Display data from the
object:
document.getElementById("demo").innerHTML =
person.language;
Learn more about Gettes and Setters in JS Object Accessors
Object.defineProperty()
Object.defineProperty()
is a new Object method in ES5.
It lets you define an object property and/or change a property's value and/or metadata.
Example
// Create an Object:
var person = {
firstName:
"John",
lastName : "Doe",
language : "NO",
};
// Change a Property:
Object.defineProperty(person, "language", {
value: "EN",
writable : true,
enumerable : true,
configurable : true
});
//
Enumerate Properties
var txt = "";
for (var x in person) {
txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML =
txt;
Next example is the same code, except it hides the language property from enumeration:
Example
// Create an Object:
var person = {
firstName:
"John",
lastName : "Doe",
language : "NO",
};
// Change a Property:
Object.defineProperty(person, "language", {
value: "EN",
writable : true,
enumerable : false,
configurable : true
});
//
Enumerate Properties
var txt = "";
for (var x in person) {
txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML =
txt;
This example creates a setter and a getter to secure upper case updates of language:
Example
/// Create an Object:
var person = {
firstName: "John",
lastName :
"Doe",
language : "NO"
};
// Change a Property:
Object.defineProperty(person, "language", {
get : function() { return
language },
set : function(value) { language = value.toUpperCase()}
});
// Change Language
person.language = "en";
// Display Language
document.getElementById("demo").innerHTML = person.language;
E5 Object Methods
ES5 added a lot of new Object Methods to JavaScript:
Managing Objects
// Create object with an existing object as prototype
Object.create(parent, donor)
// Adding or changing an object property
Object.defineProperty(object, property, descriptor)
// Adding or changing object properties
Object.defineProperties(object, descriptors)
// Accessing Properties
Object.getOwnPropertyDescriptor(object, property)
// Returns all properties as an array
Object.getOwnPropertyNames(object)
// Accessing the prototype
Object.getPrototypeOf(object)
// Returns enumerable properties as an array
Object.keys(object)
Protecting Objects
// Prevents adding properties to an object
Object.preventExtensions(object)
// Returns true if properties can be added to an object
Object.isExtensible(object)
// Prevents changes of object properties (not values)
Object.seal(object)
// Returns true if object is sealed
Object.isSealed(object)
// Prevents any changes to an object
Object.freeze(object)
// Returns true if object is frozen
Object.isFrozen(object)
Learn more in Object ECMAScript5.
Trailing Commas
ES5 allows trailing commas in object and array definitions:
Object Example
person = {
firstName: "John",
lastName: "
Doe",
age: 46,
}
Array Example
points = [
1,
5,
10,
25,
40,
100,
];
WARNING !!!
JSON does not allow trailing commas.
JSON Objects:
//
Allowed:
var person = '{"firstName":"John", "lastName":"Doe",
"age":46}'
JSON.parse(person)
// Not allowed:
var person = '{"firstName":"John",
"lastName":"Doe", "age":46,}'
JSON.parse(person)
JSON Arrays:
//
Allowed:
points = [40, 100, 1, 5, 25, 10]
// Not allowed:
points =
[40, 100, 1, 5, 25, 10,]