JSチュートリアル

JSホーム JSの紹介 JSどこへ JS出力 JSステートメント JS構文 JSコメント JS変数 JS Let JSConst JSオペレーター JS算術 JS割り当て JSデータ型 JS関数 JSオブジェクト JSイベント JS文字列 JS文字列メソッド JS文字列検索 JS文字列テンプレート JS番号 JS番号メソッド JSアレイ JS配列メソッド JS配列ソート JSアレイの反復 JSアレイ定数 JSの日付 JSの日付形式 JS DateGetメソッド JS日付設定メソッド JS数学 JSランダム JSブール値 JSの比較 JS条件 JSスイッチ JSループFor JSループフォーイン JSループの JSループWhile JSブレイク JSIterables JSセット JSマップ JS Typeof JS型変換 JSビット単位 JS RegExp JSエラー JSスコープ JSホイスト JS厳密モード JSこのキーワード JSアロー関数 JSクラス JS JSON JSデバッグ JSスタイルガイド JSのベストプラクティス JSの間違い JSパフォーマンス JS予約語

JSバージョン

JSバージョン JS 2009(ES5) JS 2015(ES6) JS 2016 JS 2017 JS 2018 JS IE /エッジ JSの歴史

JSオブジェクト

オブジェクト定義 オブジェクトのプロパティ オブジェクトメソッド オブジェクト表示 オブジェクトアクセサー オブジェクトコンストラクター オブジェクトのプロトタイプ オブジェクト反復可能 オブジェクトセット オブジェクトマップ オブジェクトリファレンス

JS関数

関数の定義 関数パラメーター 関数の呼び出し 関数呼び出し 機能適用 関数クロージャ

JSクラス

クラスイントロ クラス継承 クラス静的

JSAsync

JSコールバック JS非同期 JSの約束 JS Async / Await

JS HTML DOM

DOMイントロ DOMメソッド DOMドキュメント DOM要素 DOM HTML DOMフォーム DOM CSS DOMアニメーション DOMイベント DOMイベントリスナー DOMナビゲーション DOMノード DOMコレクション DOMノードリスト

JSブラウザBOM

JSウィンドウ JS画面 JSロケーション JSの歴史 JSナビゲーター JSポップアップアラート JSタイミング JSクッキー

JS Web API

WebAPIイントロ WebフォームAPI Web履歴API WebストレージAPI WebワーカーAPI Web Fetch API Web Geolocation API

JS AJAX

AJAXイントロ AJAX XMLHttp AJAXリクエスト AJAX応答 AJAXXMLファイル AJAX PHP AJAX ASP AJAXデータベース AJAXアプリケーション AJAXの例

JS JSON

JSONイントロ JSON構文 JSONとXML JSONデータ型 JSON解析 JSON文字列化 JSONオブジェクト JSON配列 JSONサーバー JSON PHP JSON HTML JSON JSONP

JSとjQuery

jQueryセレクター jQuery HTML jQuery CSS jQuery DOM

JSグラフィックス

JSグラフィックス JSキャンバス JSPlotly JS Chart.js JSグーグルチャート JS D3.js

JSの例

JSの例 JS HTML DOM JSHTML入力 JSHTMLオブジェクト JSHTMLイベント JSブラウザ JSエディター JS演習 JSクイズ JS証明書

JSリファレンス

JavaScriptオブジェクト HTMLDOMオブジェクト


Javascript ES6

ECMAScript 2015は、JavaScriptの2番目のメジャーリビジョンでした。

ECMAScript 2015は、ES6およびECMAScript6とも呼ばれます。

この章では、ES6の最も重要な機能について説明します。

ES6の新機能


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()のようになりますtruefalse

let text = "Hello world, welcome to the universe.";
text.includes("world")    // Returns true

String.startsWith()

文字列が指定された値で始まる場合、メソッドは戻ります。それ以外の場合は、startsWith()のようになりますtruefalse

let text = "Hello world, welcome to the universe.";

text.startsWith("Hello")   // Returns true

String.endsWith()

文字列が指定された値で終了する場合、メソッドは戻ります。それ以外の場合は、endsWith()のようになりますtruefalse

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