JavaScript ES5
ECMAScript 2009, noto anche come ES5, è stata la prima revisione importante di JavaScript.
Questo capitolo descrive le caratteristiche più importanti di ES5.
Caratteristiche ES5
- "usare severo"
- Accesso a stringa[ numero ].
- Stringhe multilinea
- String.trim()
- Array.isArray()
- Array forEach()
- Mappa array()
- Filtro array()
- Riduci la matrice()
- Array reduceRight()
- Matrice ogni ()
- Array alcuni ()
- array indexOf()
- Array lastIndexOf()
- JSON.parse()
- JSON.stringify()
- Data.ora()
- Data a ISOString()
- Data aJSON()
- Getter e setter di proprietà
- Parole riservate come nomi di proprietà
- Metodi dell'oggetto
- Oggetto defineProperty()
- Funzione.bind()
- Virgole finali
Supporto browser
ES5
è completamente supportato in tutti i browser moderni:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9.0 | Yes | Yes | Yes | Yes |
La direttiva "uso rigoroso".
"use strict"
definisce che il codice JavaScript deve essere eseguito in "modalità rigorosa".
Con la modalità rigorosa è possibile, ad esempio, non utilizzare variabili non dichiarate.
Puoi usare la modalità rigorosa in tutti i tuoi programmi. Ti aiuta a scrivere codice più pulito, ad esempio impedendoti di utilizzare variabili non dichiarate.
"use strict"
è solo un'espressione stringa. I vecchi browser non genereranno un errore se non lo comprendono.
Per saperne di più in modalità rigorosa JS .
Accesso alla proprietà su stringhe
Il charAt()
metodo restituisce il carattere in corrispondenza di un indice (posizione) specificato in una stringa:
Esempio
var str = "HELLO WORLD";
str.charAt(0); // returns H
ES5 consente l'accesso alle proprietà sulle stringhe:
Esempio
var str = "HELLO WORLD";
str[0]; // returns H
L'accesso alla proprietà sulla stringa potrebbe essere un po' imprevedibile.
Maggiori informazioni in Metodi stringa JS .
Stringhe su più righe
ES5 consente stringhe letterali su più righe se l'escape con una barra rovesciata:Esempio
"Hello \
Dolly!";
Il metodo \ potrebbe non avere il supporto universale.
I browser meno recenti potrebbero trattare gli spazi intorno alla barra rovesciata in modo diverso.
Alcuni browser meno recenti non consentono spazi dietro il carattere \.
Un modo più sicuro per suddividere una stringa letterale è utilizzare l'addizione di stringhe:
Esempio
"Hello " +
"Dolly!";
Parole riservate come nomi di proprietà
ES5 consente parole riservate come nomi di proprietà:
Esempio di oggetto
var obj = {name: "John", new: "yes"}
Taglio stringa()
Il trim()
metodo rimuove gli spazi bianchi da entrambi i lati di una stringa.
Esempio
var str = " Hello World! ";
alert(str.trim());
Maggiori informazioni in Metodi stringa JS .
Array.isArray()
Il isArray()
metodo controlla se un oggetto è un array.
Esempio
function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = document.getElementById("demo");
x.innerHTML = Array.isArray(fruits);
}
Maggiori informazioni su Array JS .
Array forEach()
Il forEach()
metodo chiama una funzione una volta per ogni elemento dell'array.
Esempio
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value) {
txt = txt + value + "<br>";
}
Ulteriori informazioni sui metodi di iterazione dell'array JS .
Mappa array()
Questo esempio moltiplica ogni valore dell'array per 2:
Esempio
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value) {
return value * 2;
}
Ulteriori informazioni sui metodi di iterazione dell'array JS .
Filtro array()
Questo esempio crea una nuova matrice da elementi con un valore maggiore di 18:
Esempio
var numbers = [45, 4, 9, 16, 25];
var over18 =
numbers.filter(myFunction);
function myFunction(value) {
return value > 18;
}
Ulteriori informazioni sui metodi di iterazione dell'array JS .
Riduci la matrice()
Questo esempio trova la somma di tutti i numeri in una matrice:
Esempio
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);
function myFunction(total, value) {
return total + value;
}
Ulteriori informazioni sui metodi di iterazione dell'array JS .
Array reduceRight()
Questo esempio trova anche la somma di tutti i numeri in una matrice:
Esempio
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);
function myFunction(total, value) {
return total + value;
}
Ulteriori informazioni sui metodi di iterazione dell'array JS .
Matrice ogni ()
Questo esempio verifica se tutti i valori sono superiori a 18:
Esempio
var numbers = [45, 4, 9, 16, 25];
var allOver18 =
numbers.every(myFunction);
function myFunction(value) {
return
value > 18;
}
Ulteriori informazioni sui metodi di iterazione dell'array JS .
Array alcuni ()
Questo esempio controlla se alcuni valori sono superiori a 18:
Esempio
var numbers = [45, 4, 9, 16, 25];
var allOver18 =
numbers.some(myFunction);
function myFunction(value) {
return
value > 18;
}
Ulteriori informazioni sui metodi di iterazione dell'array JS .
array indexOf()
Cerca in un array il valore di un elemento e ne restituisce la posizione.
Esempio
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
Ulteriori informazioni sui metodi di iterazione dell'array JS .
Array lastIndexOf()
lastIndexOf()
è uguale a indexOf()
, ma effettua la ricerca dalla fine dell'array.
Esempio
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");
Ulteriori informazioni sui metodi di iterazione dell'array JS .
JSON.parse()
Un uso comune di JSON consiste nel ricevere dati da un server web.
Immagina di aver ricevuto questa stringa di testo da un server web:
'{"name":"John", "age":30, "city":"New York"}'
La funzione JavaScript JSON.parse()
viene utilizzata per convertire il testo in un oggetto JavaScript:
var obj = JSON.parse('{"name":"John", "age":30, "city":"New
York"}');
Leggi di più nel nostro tutorial JSON .
JSON.stringify()
Un uso comune di JSON è inviare dati a un server web.
Quando si inviano dati a un server Web, i dati devono essere una stringa.
Immagina di avere questo oggetto in JavaScript:
var obj = {name:"John", age:30, city:"New York"};
Usa la funzione JavaScript JSON.stringify()
per convertirlo in una stringa.
var myJSON = JSON.stringify(obj);
Il risultato sarà una stringa che segue la notazione JSON.
myJSON è ora una stringa e pronta per essere inviata a un server:
Esempio
var obj = {name:"John", age:30, city:"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Leggi di più nel nostro tutorial JSON .
Data.ora()
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,]