JavaScript ES6
ECMAScript 2015 był drugą poważną wersją JavaScript.
ECMAScript 2015 jest również znany jako ES6 i ECMAScript 6.
Ten rozdział opisuje najważniejsze cechy ES6.
Nowe funkcje w ES6
- Słowo kluczowe niech
- Słowo kluczowe const
- Funkcje strzałek
- Za/z
- Mapa obiektów
- Ustaw obiekty
- Klasy
- Obietnice
- Symbol
- Parametry domyślne
- Funkcja odpoczynku parametr
- Ciąg.zawiera()
- String.startsWith()
- String.endsWith()
- tablica.z()
- Klawisze tablicy()
- Znajdź tablicę()
- Znajdowanie indeksu tablicy()
- Nowe metody matematyczne
- Nowe właściwości numeru
- Nowe metody liczbowe
- Nowe metody globalne
- Iterable Obiekt.wpisy
- Moduły JavaScript
Obsługa przeglądarek dla ES6 (2015)
Safari 10 i Edge 14 były pierwszymi przeglądarkami, które w pełni obsługują ES6:
Chrome 58 | Edge 14 | Firefox 54 | Safari 10 | Opera 55 |
Jan 2017 | Aug 2016 | Mar 2017 | Jul 2016 | Aug 2018 |
JavaScript niech
Słowo let
kluczowe pozwala zadeklarować zmienną o zasięgu blokowym.
Przykład
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Przeczytaj więcej let
w rozdziale: JavaScript Let .
Stała JavaScript
Słowo const
kluczowe pozwala zadeklarować stałą (zmienną JavaScript o stałej wartości).
Stałe są podobne do zmiennych let, z tą różnicą, że nie można zmienić ich wartości.
Przykład
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Przeczytaj więcej const
w rozdziale: JavaScript Const .
Funkcje strzałek
Funkcje strzałek umożliwiają krótką składnię do pisania wyrażeń funkcyjnych.
Nie potrzebujesz function
słowa kluczowego, return
słowa kluczowego i
nawiasów klamrowych .
Przykład
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
Funkcje strzałek nie mają własnych this
. Nie nadają się do definiowania metod obiektowych .
Funkcje strzałek nie są podnoszone. Muszą być zdefiniowane przed użyciem.
Używanie const
jest bezpieczniejsze niż używanie var
, ponieważ wyrażenie funkcji jest zawsze wartością stałą.
return
Słowo kluczowe i nawiasy klamrowe można pominąć tylko wtedy, gdy funkcja jest pojedynczą instrukcją. Z tego powodu dobrym nawykiem może być trzymanie ich zawsze:
Przykład
const x = (x, y) => { return x * y };
Dowiedz się więcej o funkcjach strzałkowych w rozdziale: Funkcja strzałkowa JavaScript .
Pętla For/O
Instrukcja JavaScript for/of
przechodzi przez wartości obiektów iterowalnych.
for/of
umożliwia pętlę po strukturach danych, które można iterować, takich jak tablice, ciągi, mapy, listy węzłów i inne.
Pętla for/of
ma następującą składnię:
for (variable of iterable) {
// code block to be executed
}
zmienna - Dla każdej iteracji przypisywana jest zmiennej wartość kolejnej właściwości. Zmienną można zadeklarować za pomocą
const
, let
lub var
.
iterowalny — obiekt, który ma właściwości iterowalne.
Zapętlanie tablicy
Przykład
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + " ";
}
Zapętlanie sznurka
Przykład
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + " ";
}
Dowiedz się więcej w rozdziale: JavaScript Loop For/In/Of .
Obiekty map JavaScript
Możliwość użycia obiektu jako klucza jest ważną cechą mapy.
Przykład
// Create Objects
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};
// Create a new Map
const fruits = new Map();
// Add new Elements to the Map
fruits.set(apples, 500);
fruits.set(bananas, 300);
fruits.set(oranges, 200);
Dowiedz się więcej o obiektach Map w rozdziale: JavaScript Map() .
JavaScript Ustaw obiekty
Przykład
// Create a Set
const letters = new Set();
// Add some values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
Dowiedz się więcej o obiektach Set w rozdziale: JavaScript Set() .
Klasy JavaScript
Klasy JavaScript to szablony obiektów JavaScript.
Użyj słowa kluczowego class
, aby utworzyć klasę.
Zawsze dodawaj metodę o nazwie constructor()
:
Składnia
class ClassName {
constructor() { ... }
}
Przykład
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
Powyższy przykład tworzy klasę o nazwie „Car”.
Klasa ma dwie początkowe właściwości: „nazwa” i „rok”.
Klasa JavaScript nie jest obiektem.
Jest to szablon dla obiektów JavaScript.
Korzystanie z klasy
Kiedy masz klasę, możesz jej użyć do tworzenia obiektów:
Przykład
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
Dowiedz się więcej o klasach w rozdziale: Klasy JavaScript .
Obietnice JavaScript
Promise to obiekt JavaScript, który łączy „Kod produkcyjny” i „Kod zużywający”.
„Wytworzenie kodu” może zająć trochę czasu, a „Kod zużywający” musi poczekać na wynik.
Składnia obietnicy
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 */ }
);
Przykład użycia obietnicy
const myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
Dowiedz się więcej o Promises w rozdziale: JavaScript Promises .
Typ symbolu
Symbol JavaScript to prymitywny typ danych, taki jak Number, String lub Boolean.
Stanowi unikalny „ukryty” identyfikator, do którego żaden inny kod nie może przypadkowo uzyskać dostępu.
Na przykład, jeśli różni programiści chcą dodać właściwość person.id do obiektu osoby należącego do kodu innej firmy, mogą mieszać wartości między sobą.
Używanie Symbol() do tworzenia unikalnych identyfikatorów rozwiązuje ten problem:
Przykład
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
Symbole są zawsze niepowtarzalne.
Jeśli utworzysz dwa symbole o tym samym opisie, będą miały różne wartości.
Symbol("id") == Symbol("id") // false
Domyślne wartości parametrów
ES6 umożliwia, aby parametry funkcji miały wartości domyślne.
Przykład
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y;
}
myFunction(5); // will return 15
Funkcja odpoczynku parametr
Parametr rest (...) pozwala funkcji traktować nieskończoną liczbę argumentów jako tablicę:
Przykład
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);
Ciąg.zawiera()
Metoda includes()
zwraca true
, jeśli ciąg zawiera określoną wartość, w przeciwnym razie false
:
Przykład
let text = "Hello world, welcome to the universe.";
text.includes("world") // Returns true
String.startsWith()
Metoda startsWith()
zwraca true
, jeśli ciąg zaczyna się od określonej wartości, w przeciwnym razie false
:
Przykład
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello") // Returns true
String.endsWith()
Metoda endsWith()
zwraca true
, jeśli ciąg kończy się określoną wartością, w przeciwnym razie false
:
Przykład
var text = "John Doe";
text.endsWith("Doe") // Returns true
tablica.z()
The Array.from()
method returns an Array object from any object with a length
property or any iterable object.
Example
Create an Array from a String:
Array.from("ABCDEFG") // Returns [A,B,C,D,E,F,G]
Array keys()
The keys()
method returns an Array Iterator object with the keys of an array.
Example
Create an Array Iterator object, containing the keys of the array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();
let text = "";
for (let x of keys) {
text += x + "<br>";
}
Array find()
The find()
method returns the value of the first array element that passes a
test function.
This example finds (returns the value of ) the first element that is larger than 18:
Example
const numbers = [4, 9, 16, 25, 29];
let first =
numbers.find(myFunction);
function myFunction(value, index, array) {
return
value > 18;
}
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
Array findIndex()
The findIndex()
method returns the index of the first array element that
passes a test function.
This example finds the index of the first element that is larger than 18:
Example
const numbers = [4, 9, 16, 25, 29];
let first =
numbers.findIndex(myFunction);
function myFunction(value, index, array) {
return
value > 18;
}
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
New Math Methods
ES6 added the following methods to the Math object:
Math.trunc()
Math.sign()
Math.cbrt()
Math.log2()
Math.log10()
The Math.trunc() Method
Math.trunc(x)
returns the integer part of x:
Example
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
The Math.sign() Method
Math.sign(x)
returns if x is negative, null or positive:
Example
Math.sign(-4); // returns -1
Math.sign(0); // returns 0
Math.sign(4); // returns 1
The Math.cbrt() Method
Math.cbrt(x)
returns the cube root of x:
Example
Math.cbrt(8); // returns 2
Math.cbrt(64); // returns 4
Math.cbrt(125); // returns 5
The Math.log2() Method
Math.log2(x)
returns the base 2 logarithm of x:
Example
Math.log2(2); // returns 1
The Math.log10() Method
Math.log10(x)
returns the base 10 logarithm of x:
Example
Math.log10(10); // returns 1
New Number Properties
ES6 added the following properties to the Number object:
EPSILON
MIN_SAFE_INTEGER
MAX_SAFE_INTEGER
Example
let x = Number.EPSILON;
Example
let x = Number.MIN_SAFE_INTEGER;
Example
let x = Number.MAX_SAFE_INTEGER;
New Number Methods
ES6 added 2 new methods to the Number object:
Number.isInteger()
Number.isSafeInteger()
The Number.isInteger() Method
The Number.isInteger()
method returns true
if the argument is an integer.
Example
Number.isInteger(10); // returns true
Number.isInteger(10.5); // returns false
The Number.isSafeInteger() Method
A safe integer is an integer that can be exactly represented as a double precision number.
The Number.isSafeInteger()
method returns true
if the argument is a safe integer.
Example
Number.isSafeInteger(10); // returns true
Number.isSafeInteger(12345678901234567890); // returns false
Safe integers are all integers from -(253 - 1) to +(253 - 1).
This is safe: 9007199254740991. This is not safe: 9007199254740992.
New Global Methods
ES6 added 2 new global number methods:
isFinite()
isNaN()
The isFinite() Method
The global isFinite()
method returns false
if the argument is Infinity
or NaN
.
Otherwise it returns true
:
Example
isFinite(10/0); // returns false
isFinite(10/1); // returns true
The isNaN() Method
The global isNaN()
method returns true
if the argument is NaN
. Otherwise it returns false
:
Example
isNaN("Hello"); // returns true