Javascript ES6
ECMAScript 2015は、JavaScriptの2番目のメジャーリビジョンでした。
ECMAScript 2015は、ES6およびECMAScript6とも呼ばれます。
この章では、ES6の最も重要な機能について説明します。
ES6の新機能
- letキーワード
- constキーワード
- 矢印関数
- の
- マップオブジェクト
- オブジェクトの設定
- クラス
- 約束
- シンボル
- デフォルトパラメータ
- 関数RESTパラメーター
- String.includes()
- String.startsWith()
- String.endsWith()
- Array.from()
- 配列keys()
- 配列find()
- 配列findIndex()
- 新しい数学メソッド
- 新しい番号のプロパティ
- 新しい数値メソッド
- 新しいグローバルメソッド
- Iterables Object.entries
- JavaScriptモジュール
ES6のブラウザサポート(2015)
Safari10とEdge14は、ES6を完全にサポートする最初のブラウザでした。
Chrome 58 | Edge 14 | Firefox 54 | Safari 10 | Opera 55 |
Jan 2017 | Aug 2016 | Mar 2017 | Jul 2016 | Aug 2018 |
JavaScriptレット
このlet
キーワードを使用すると、ブロックスコープで変数を宣言できます。
例
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
詳細については、「 JavaScriptLet」let
の章を参照してください。
JavaScript const
このconst
キーワードを使用すると、定数(定数値を持つJavaScript変数)を宣言できます。
定数は、値を変更できないことを除いて、let変数に似ています。
例
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
詳細については、 JavaScriptConstconst
の章をご覧ください。
矢印関数
矢印関数を使用すると、関数式を記述するための短い構文を使用できます。
function
キーワード、return
キーワード、
中括弧は必要ありません。
例
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
矢印関数には独自のはありませんthis
。これらは、オブジェクトメソッドの定義にはあまり適していません。
矢印機能は吊り上げられていません。使用する前に定義する必要があります。
関数式は常に定数値であるため、を使用する方がを使用const
するよりも安全です。var
return
関数が単一のステートメントである場合にのみ、キーワードと中括弧を省略できます。このため、常にそれらを保持することは良い習慣かもしれません:
例
const x = (x, y) => { return x * y };
矢印関数の詳細については、JavaScriptの矢印関数の章を参照してください。
For / Ofループ
JavaScriptfor/of
ステートメントは、反復可能なオブジェクトの値をループします。
for/of
配列、文字列、マップ、ノードリストなどの反復可能なデータ構造をループできます。
ループのfor/of
構文は次のとおりです。
for (variable of iterable) {
// code block to be executed
}
variable-反復ごとに、次のプロパティの値が変数に割り当てられます。変数const
は、、、let
またはで宣言できます
var
。
iterable-反復可能なプロパティを持つオブジェクト。
配列をループする
例
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + " ";
}
文字列をループする
例
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + " ";
}
詳細については、 JavaScriptループのFor / In / Ofの章を参照してください。
JavaScriptマップオブジェクト
オブジェクトをキーとして使用できることは、重要なマップ機能です。
例
// 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);
Mapオブジェクトの詳細については、JavaScript Map()の章を参照してください。
JavaScriptセットオブジェクト
例
// Create a Set
const letters = new Set();
// Add some values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
Setオブジェクトの詳細については、JavaScript Set()の章を参照してください。
JavaScriptクラス
JavaScriptクラスは、JavaScriptオブジェクトのテンプレートです。
キーワードclass
を使用してクラスを作成します。
常に:という名前のメソッドを追加しconstructor()
ます
構文
class ClassName {
constructor() { ... }
}
例
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
上記の例では、「Car」という名前のクラスを作成します。
このクラスには、「name」と「year」の2つの初期プロパティがあります。
JavaScriptクラスはオブジェクトではありません。
JavaScriptオブジェクトのテンプレートです。
クラスの使用
クラスがある場合は、そのクラスを使用してオブジェクトを作成できます。
例
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
クラスの詳細については、「JavaScriptクラス」の章を参照してください。
JavaScriptの約束
Promiseは、「コードの生成」と「コードの消費」をリンクするJavaScriptオブジェクトです。
「コードの生成」には時間がかかる場合があり、「コードの消費」は結果を待つ必要があります。
Promise構文
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 */ }
);
Promiseの使用例
const myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
Promisesの詳細については、「JavaScriptPromises」の章を参照してください。
シンボルタイプ
JavaScriptシンボルは、数値、文字列、ブール値と同じようなプリミティブデータ型です。
これは、他のコードが誤ってアクセスできない一意の「隠し」識別子を表します。
たとえば、異なるコーダーがサードパーティのコードに属するpersonオブジェクトにperson.idプロパティを追加したい場合、それらは互いに値を混合することができます。
Symbol()を使用して一意の識別子を作成すると、この問題が解決します。
例
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
シンボルは常に一意です。
同じ説明で2つのシンボルを作成すると、それらの値は異なります。
Symbol("id") == Symbol("id") // false
デフォルトのパラメータ値
ES6では、関数パラメーターにデフォルト値を設定できます。
例
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y;
}
myFunction(5); // will return 15
関数RESTパラメーター
残りのパラメーター(...)を使用すると、関数は無数の引数を配列として扱うことができます。
例
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);
String.includes()
文字列に指定された値が含まれている場合、メソッドは戻ります。それ以外の場合は、次includes()
のようになります。true
false
例
let text = "Hello world, welcome to the universe.";
text.includes("world") // Returns true
String.startsWith()
文字列が指定された値で始まる場合、メソッドは戻ります。それ以外の場合は、次startsWith()
のようになります。true
false
例
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello") // Returns true
String.endsWith()
文字列が指定された値で終了する場合、メソッドは戻ります。それ以外の場合は、次endsWith()
のようになります。true
false
例
var text = "John Doe";
text.endsWith("Doe") // Returns true
Array.from()
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