JavaScript ES5
- Pagina precedente Versione JS
- Pagina successiva JS 2015 (ES6)
Cos'è ECMAScript 5?
ECMAScript 5 也称为 ES5 和 ECMAScript 2009。
本章介绍 ES5 的一些最重要的特性。
ECMAScript 5 特性
这些是 2009 年发布的新特性:
- "use strict" 指令
- String.trim()
- Array.isArray()
- Array.forEach()
- Array.map()
- Array.filter()
- Array.reduce()
- Array.reduceRight()
- Array.every()
- Array.some()
- Array.indexOf()
- Array.lastIndexOf()
- JSON.parse()
- JSON.stringify()
- Date.now()
- getter e setter delle proprietà
- nuove proprietà e metodi degli oggetti
ECMAScript 5 语法更改
- 对字符串的属性访问 [ ]
- 数组和对象字面量中的尾随逗号
- 多行字符串字面量
- 作为属性名称的保留字
"use strict" 指令
"use strict
" 定义 JavaScript 代码应该以“严格模式”执行。
例如,使用严格模式,不能使用未声明的变量。
您可以在所有程序中使用严格模式。它可以帮助您编写更清晰的代码,例如阻止您使用未声明的变量。
"use strict
” 只是一个字符串表达式。旧浏览器如果不理解它们就不会抛出错误。
请阅读 JS 严格模式 中的更多内容。
String.trim()
String.trim()
删除字符串两端的空白字符。
Esempio
var str = " Hello World! "; alert(str.trim());
Per favore, Metodi di stringa JS 中阅读更多内容。
Array.isArray()
isArray()
方法检查对象是否为数组。
Esempio
function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x = document.getElementById("demo"); x.innerHTML = Array.isArray(fruits); }
Per favore, JS 数组 中阅读更多内容。
Array.forEach()
forEach()
方法为每个数组元素调用一次函数。
Esempio
var txt = ""; var numbers = [45, 4, 9, 16, 25]; numbers.forEach(myFunction); function myFunction(value) { txt = txt + value + "<br>"; }
Per favore, Metodi di iterazione degli array JS Scopri di più.
Array.map()
这个例子给每个数组值乘以 2:
Esempio
var numbers1 = [45, 4, 9, 16, 25]; var numbers2 = numbers1.map(myFunction); function myFunction(value) { return value * 2; }
Per favore, Metodi di iterazione degli array JS Scopri di più.
Array.filter()
此例用值大于 18 的元素创建一个新数组:
Esempio
var numbers = [45, 4, 9, 16, 25]; var over18 = numbers.filter(myFunction); function myFunction(value) { return value > 18; }
Per favore, Metodi di iterazione degli array JS Scopri di più.
Array.reduce()
这个例子确定数组中所有数的总和:
Esempio
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduce(myFunction); function myFunction(total, value) { return total + value; }
Per favore, Metodi di iterazione degli array JS Scopri di più.
Array.reduceRight()
Questo esempio determina la somma di tutti i numeri dell'array:}
Esempio
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduceRight(myFunction); function myFunction(total, value) { return total + value; }
Per favore, Metodi di iterazione degli array JS Scopri di più.
Array.every()
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; }
Per favore, Metodi di iterazione degli array JS Scopri di più.
Array.some()
Questo esempio verifica 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; }
Per favore, Metodi di iterazione degli array JS Scopri di più.
Array.indexOf()
Ricerca il valore di un elemento dell'array e restituisce la sua posizione:
Esempio
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var a = fruits.indexOf("Apple");
Per favore, Metodi di iterazione degli array JSScopri di più.
Array.lastIndexOf()
Array.lastIndexOf()
Con Array.indexOf()
Simile, ma cerca dall'fine dell'array.
Esempio
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var a = fruits.lastIndexOf("Apple");
Per favore, Metodi di iterazione degli array JS Scopri di più.
JSON.parse()
Un uso comune di JSON è ricevere dati da un server Web。
Immaginiamo che riceviate questo stringa di testo dal server Web:
'{"name":"Bill", "age":62, "city":"Seatle"}'
Funzioni JavaScript JSON.parse()
Utilizzata per convertire il testo in un oggetto JavaScript:
var obj = JSON.parse('{"name":"Bill", "age":62, "city":"Seatle"}');
Per favore, visita il nostro Tutorial JSON Scopri di più.
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。
Immaginiamo che in JavaScript abbiamo questo oggetto:
var obj = {"name":"Bill", "age":62, "city":"Seatle"};
Utilizza la funzione JavaScript JSON.stringify() per trasformarla in una stringa。
var myJSON = JSON.stringify(obj);
Il risultato sarà una stringa che segue la rappresentazione JSON。
myJSON ora è una stringa pronta per essere inviata al server:
Esempio
var obj = {"name":"Bill", "age":62, "city":"Seatle"}; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON;
Per favore, visita il nostro Tutorial JSON Scopri di più.
Date.now()
Date.now() restituisce il numero di millisecondi trascorsi dal 1 gennaio 1970 00:00:00:00.
Esempio
var timInMSs = Date.now();
Date.now()
è uguale al risultato di getTime() eseguito sull'oggetto Date.
Per favore, Data JS per saperne di più.
getter e setter delle proprietà
ES5 ti permette di definire metodi dell'oggetto utilizzando una sintassi simile a quella per ottenere o impostare proprietà.
Questo esempio crea un getter:
Esempio
// Create object: var person = { firstName: "Bill", lastName : "Gates" get fullName() { return this.firstName + " " + this.lastName; } }); // Utilizza il getter per visualizzare i dati provenienti dall'oggetto: document.getElementById("demo").innerHTML = person.fullName;
Questo esempio crea un setter e un getter:
Esempio
var person = { firstName: "Bill", lastName : "Gates" language : "NO", get lang() { return this.language; }, set lang(value) { this.language = value; } }); // Utilizza lo setter per impostare le proprietà dell'oggetto: person.lang = "en"; // Utilizza il getter per visualizzare i dati provenienti dall'oggetto: document.getElementById("demo").innerHTML = person.lang;
Questo esempio utilizza lo setter per garantire che l'aggiornamento della lingua sia in maiuscolo:
Esempio
var person = { firstName: "Bill", lastName : "Gates" language : "NO", set lang(value) { this.language = value.toUpperCase(); } }); // Utilizza lo setter per impostare le proprietà dell'oggetto: person.lang = "en"; // Visualizza i dati provenienti dall'oggetto: document.getElementById("demo").innerHTML = person.language;
Per favore, Accessori degli oggetti JS per saperne di più sui getter e setter.
nuove proprietà e metodi degli oggetti
Object.defineProperty()
è un nuovo metodo dell'oggetto in ES5.
consente di definire proprietà dell'oggetto e/o modificare i valori e/o i metadati delle proprietà.
Esempio
// Create object: var person = { firstName: "Bill", lastName : "Gates" language : "NO", }); // Change 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;
The next example is the same code, but it hides the language property in enumeration:
Esempio
// Create object: var person = { firstName: "Bill", lastName : "Gates" language : "NO", }); // Change 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 getter to ensure the uppercase update of the language:
Esempio
// Create object: var person = { firstName: "Bill", lastName : "Gates" language : "NO" }); // Change 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;
New object methods in ES5
ECMAScript 5 adds many new object methods to JavaScript:
// Adds or changes object property Object.defineProperty(object, property, descriptor) // Adds or changes multiple object properties Object.defineProperties(object, descriptors) // Accessing property Object.getOwnPropertyDescriptor(object, property) // Returns all properties as an array Object.getOwnPropertyNames(object) // Returns enumerable properties as an array Object.keys(object) // Accessing prototype Object.getPrototypeOf(object) // Impedisce di aggiungere proprietà all'oggetto Object.preventExtensions(object) // Se è possibile aggiungere proprietà all'oggetto, restituisce true Object.isExtensible(object) // Impedisce la modifica delle proprietà dell'oggetto (non dei valori) Object.seal(object) // Se l'oggetto è sigillato, restituisce true Object.isSealed(object) // Impedisce qualsiasi modifica all'oggetto Object.freeze(object) // Se l'oggetto è bloccato, restituisce true Object.isFrozen(object)
Per favore, Oggetto ECMAScript5 Scopri di più.
L'accesso alle proprietà delle stringhe
charAt()
Il metodo restituisce il carattere specificato dall'indice (posizione) della stringa:
Esempio
var str = "HELLO WORLD"; str.charAt(0); // Restituisce H
ECMAScript 5 consente l'accesso alle proprietà delle stringhe:
Esempio
var str = "HELLO WORLD"; str[0]; // Restituisce H
l'accesso alle proprietà delle stringhe potrebbe essere un po' imprevedibile.
Per favore, Metodi di stringa JS Scopri di più.
Virgole finali (Trailing Commas)
ECMAScript 5 consente l'uso di virgole finali nella definizione di oggetti e array:
Oggetto istanza
person = { firstName: "Bill", lastName: "Gates", age: 62, }
Array istanza
points = [ 1, 5, 10, 25, 40, 100, ];
警告!!!
Internet Explorer 8 将崩溃。
JSON 不允许使用尾随逗号。
JSON 对象:
// 允许: var person = '{"firstName":"Bill", "lastName":"Gates", "age":62}' JSON.parse(person) // 不允许: var person = '{"firstName":"Bill", "lastName":"Gates", "age":62,}' JSON.parse(person)
JSON 数组:
// 允许: points = [40, 100, 1, 5, 25, 10] // 不允许: points = [40, 100, 1, 5, 25, 10,]
Stringhe multiligne
Se si utilizza l'escape con backslash, ECMAScript 5 permette stringhe di testo multiligne (literals):
Esempio
"Hello \ Kitty!"
Il metodo backslash potrebbe non essere supportato universalmente.
Browser più vecchi potrebbero gestire in modo diverso gli spazi intorno al backslash.
Alcuni browser più vecchi non permettono spazi dopo il carattere di backslash.
Un metodo più sicuro per decomporre una stringa di testo è utilizzare l'aggiunta di stringhe:
Esempio
"Hello " + "Kitty!"
Parole riservate come nomi di attributo
ECMAScript 5 permette di utilizzare parole riservate come nomi di attributo:
Esempio di oggetto
var obj = {name: "Bill", new: "yes"}
Supporto browser per ES5 (ECMAScript 5)
Chrome 23, IE 10 e Safari 6 sono i primi browser a supportare completamente ECMAScript 5:
Chrome 23 | IE10 / Edge | Firefox 21 | Safari 6 | Opera 15 |
Settembre 2012 | Settembre 2012 | Aprile 2013 | Luglio 2012 | Luglio 2013 |
- Pagina precedente Versione JS
- Pagina successiva JS 2015 (ES6)