Computed property names
変数の値をオブジェクトのキーにすることができる。
var a = "foo";
var b = {[a], 1};
console.log(b.a); // 1
Spread operator
a = [1,2,3];
[0, ...a, 4];
// [ 0, 1, 2, 3, 4 ]
console.log("%dc%dc%d", ...a);
// 1c2c3
a = new Map([["a", 1], ["b", 2]])
[...a]
// [["a", 1], ["b", 2]]
let f = function* () {
let i = 0;
while(1) {
if (i > 3) {break;}
yield i;
i++;
}
}
[...f()]
// [ 0, 1, 2, 3 ]
Destructuring assignment
var [a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
var d = {abc: 123, a1: "aaa"};
var {abc, a1} = d;
console.log(abc); // 123
console.log(a1); // aaa
// オブジェクトの属性に対しても有効
let {length: l} = [1,2,3];
// l => 3
// Generator
let foo = function* () {
let i = 0;
while(1) {
i++;
yield i;
}
};
[a, b, c] = foo();
// a = 1, b = 2, c = 3
// default value
let [a=1, b] = [];
// a = 1
// デフォルトの値に関数をしているすることが可能です。
// 指定された関数はデフォルトの値を利用する
let [a=func()] = []; // funcが実行される
let [b=func()] = []; // funcが実行されない
let {a, b} = {a: 1, b: 2};
let a = "b";
({[a]: c} = {b: 3});
[,,c] = [1, 2, 3]; // c = 1
let d = {};
let e = []
// {からはじめない({とする
({a: d.e, b: e[0]} = {a: 1, b: 2}) // d.e = 1, e[0] = 2
for …of
NodeListを利用することができる
for (a of [1,2,3]) {
console.log(a);
}
// 1
// 2
// 3
Symbol
ユニークで不変な値
Symbol(<description>)
descriptionはdebug時に表示されるために使われる。
普段のプログラムには利用しない。
Symbol.for(key)
Symbolの保存領域にkeyをキーにしてSymbolを保存する。
保存したSymbolを返す。
Symbol.keyrFor(symbol)
symbolに関連しているキーが返る。
var m = new Map().set("a", 1).set("b", 2).set("c", 3);
[...m]
// [["a", 1], ["b", 2], ["c", 3]]
ECMAScript 6 compatibility table
Chromium Dashboard
ECMAScript 6 support in Mozilla
Template strings
String.rawの挙動
console.log(String.raw`111\n
222`);
// 111\n
// 222
console.log(`111\n
222`);
// 111
//
// 222
var foo = "123";
`foo is ${foo}`;
// "foo is 123"
var tag = (strings, ...values) => {
console.log(strings);
console.log(values);
};
var a = 1;
var b = 2;
var c = 10;
var d = 5;
tag`foo ${a + b} and ${c + b}`;
// Array [ "foo ", " and ", "" ]
// Array [ 3, 12 ]
Patameter
function foo({a=1, b=2}){}
function foo({a=1, b=a}){}
// 値がundefinedのときデフォルトの値を使用する
Class
class Foo {
*gen () {}
}
継承している場合はthisを利用する前にsuper()を実行する。
Map
let a = new Map().set("a", 1).set("b", 2);
[...a]
// [["a", 1], ["b", 2]]
Iterator
generatorでiteratorを展開する際はyield*を利用する。
function* g() {
let i = 0;
let a = [1,2,3,4];
yield "a";
while(1) {
yield* a;
if (i < 5) {
break;
}
}
};
for (let c of g()) {
console.log(c);
}
// a
// 1
// 2
// 3
// 4
function* gen() {
console.log("a");
console.log(yield);
}
let g = gen();
g.next();
// a
g.next("b");
// b
for of
Generator.prototype.return(value)はvalueを返してgeneratorを終了させる
var a = yield valueの形式はvalueを返したときにストップしてgen.next(b)でbがaに代入して再スタートする
Reflect.ownKeys()はObject.getOwnPropertyNames()+Object.getOwnPropertySymbols()