JavaScript ES5
ECMAScript 2009, také známý jako ES5, byl první velkou revizí JavaScriptu.
Tato kapitola popisuje nejdůležitější funkce ES5.
Vlastnosti ES5
- "použít striktně"
- Řetězec[ číslo ] přístup
- Víceřádkové řetězce
- String.trim()
- Array.isArray()
- Pole pro každého()
- Mapa pole()
- Array filter()
- Array reduction()
- Array reductionRight()
- Pole každé()
- Sestavte nějaké()
- Array indexOf()
- Pole lastIndexOf()
- JSON.parse()
- JSON.stringify()
- Date.now()
- Datum do ISOString()
- Datum do JSON()
- Zajišťovatelé a seřizovači nemovitostí
- Vyhrazená slova jako názvy vlastností
- Objektové metody
- Object defineProperty()
- Function.bind()
- Koncové čárky
Podpora prohlížeče
ES5
je plně podporován ve všech moderních prohlížečích:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9.0 | Yes | Yes | Yes | Yes |
Směrnice "použít přísné použití".
"use strict"
definuje, že kód JavaScript by měl být spuštěn v "přísném režimu".
S přísným režimem můžete například nepoužívat nedeklarované proměnné.
Přísný režim můžete použít ve všech svých programech. Pomáhá vám psát čistší kód, například vám brání v používání nedeklarovaných proměnných.
"use strict"
je pouze řetězcový výraz. Staré prohlížeče nevyhodí chybu, pokud jí nerozumí.
Přečtěte si více v JS Strict Mode .
Přístup k vlastnostem na řetězcích
Metoda charAt()
vrací znak na zadaném indexu (pozici) v řetězci:
Příklad
var str = "HELLO WORLD";
str.charAt(0); // returns H
ES5 umožňuje přístup k vlastnostem řetězců:
Příklad
var str = "HELLO WORLD";
str[0]; // returns H
Přístup k vlastnosti na řetězci může být trochu nepředvídatelný.
Přečtěte si více v JS String Methods .
Řetězce Přes Více řádků
ES5 umožňuje řetězcové literály na více řádcích, pokud jsou zakódovány zpětným lomítkem:Příklad
"Hello \
Dolly!";
Metoda \ nemusí mít univerzální podporu.
Starší prohlížeče mohou s mezerami kolem zpětného lomítka zacházet jinak.
Některé starší prohlížeče nepovolují mezery za znakem \.
Bezpečnějším způsobem, jak rozdělit řetězcový literál, je použít sčítání řetězců:
Příklad
"Hello " +
"Dolly!";
Vyhrazená slova jako názvy vlastností
ES5 umožňuje vyhrazená slova jako názvy vlastností:
Příklad objektu
var obj = {name: "John", new: "yes"}
Řetězec ()
Metoda trim()
odstraňuje bílé znaky z obou stran řetězce.
Příklad
var str = " Hello World! ";
alert(str.trim());
Přečtěte si více v JS String Methods .
Array.isArray()
Metoda isArray()
kontroluje, zda je objekt pole.
Příklad
function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = document.getElementById("demo");
x.innerHTML = Array.isArray(fruits);
}
Přečtěte si více v JS Arrays .
Pole pro každého()
Metoda forEach()
volá funkci jednou pro každý prvek pole.
Příklad
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value) {
txt = txt + value + "<br>";
}
Další informace naleznete v části Metody iterace pole JS .
Mapa pole()
Tento příklad vynásobí každou hodnotu pole 2:
Příklad
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value) {
return value * 2;
}
Další informace naleznete v části Metody iterace pole JS .
Array filter()
Tento příklad vytvoří nové pole z prvků s hodnotou větší než 18:
Příklad
var numbers = [45, 4, 9, 16, 25];
var over18 =
numbers.filter(myFunction);
function myFunction(value) {
return value > 18;
}
Další informace naleznete v části Metody iterace pole JS .
Array reduction()
Tento příklad najde součet všech čísel v poli:
Příklad
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);
function myFunction(total, value) {
return total + value;
}
Další informace naleznete v části Metody iterace pole JS .
Array reductionRight()
Tento příklad také najde součet všech čísel v poli:
Příklad
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);
function myFunction(total, value) {
return total + value;
}
Další informace naleznete v části Metody iterace pole JS .
Pole každé()
Tento příklad kontroluje, zda jsou všechny hodnoty vyšší než 18:
Příklad
var numbers = [45, 4, 9, 16, 25];
var allOver18 =
numbers.every(myFunction);
function myFunction(value) {
return
value > 18;
}
Další informace naleznete v části Metody iterace pole JS .
Sestavte nějaké()
Tento příklad kontroluje, zda jsou některé hodnoty vyšší než 18:
Příklad
var numbers = [45, 4, 9, 16, 25];
var allOver18 =
numbers.some(myFunction);
function myFunction(value) {
return
value > 18;
}
Další informace naleznete v části Metody iterace pole JS .
Array indexOf()
Vyhledá v poli hodnotu prvku a vrátí její pozici.
Příklad
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
Další informace naleznete v části Metody iterace pole JS .
Pole lastIndexOf()
lastIndexOf()
je stejný jako indexOf()
, ale hledá od konce pole.
Příklad
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");
Další informace naleznete v části Metody iterace pole JS .
JSON.parse()
Běžným použitím JSON je příjem dat z webového serveru.
Představte si, že jste obdrželi tento textový řetězec z webového serveru:
'{"name":"John", "age":30, "city":"New York"}'
Funkce JavaScript JSON.parse()
se používá k převodu textu na objekt JavaScript:
var obj = JSON.parse('{"name":"John", "age":30, "city":"New
York"}');
Přečtěte si více v našem výukovém programu JSON .
JSON.stringify()
Běžným použitím JSON je odesílání dat na webový server.
Při odesílání dat na webový server musí být daty řetězec.
Představte si, že máme tento objekt v JavaScriptu:
var obj = {name:"John", age:30, city:"New York"};
Pomocí funkce JavaScript JSON.stringify()
jej převeďte na řetězec.
var myJSON = JSON.stringify(obj);
Výsledkem bude řetězec následující za zápisem JSON.
myJSON je nyní řetězec a je připraven k odeslání na server:
Příklad
var obj = {name:"John", age:30, city:"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Přečtěte si více v našem výukovém programu JSON .
Date.now()
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,]