ES6記述一覧
const, let
varで定義していたがES6からはconst,letで定義する。
constは変わらない変数
letは今後変わる可能性がある変数
テンプレートリテラル
’今日は’ + ‘currentDay’ + ‘です’ とかいていたものが
`今日は${currentDay}です` とかけるようになった。
アロー関数でfunctionを省略できるようになった
numbers.map(function(number) {
return number + 1;
});
って書いたものが
numbers.map((number) => {
return number + 1;
});
とかけて引数が一つの場合は{}とreturnと()も省略できる
numbers.map(number => number + 1);
とかける
オブジェクトリテラル
const fields = ['firstName', 'lastName', 'phoneNumber'];
const props = { fields: fields };
と書いていたが、keyとvalueが同じ値なら :valueを省略できる
const fields = ['firstName', 'lastName', 'phoneNumber'];
const props = { fields };
関数(function)も省略
const color = 'red';
const Car = {
color: color,
drive: function() {
return 'ブーーン!';
},
getColor: function() {
return this.color;
}
};
と書いていた物が
const color = 'red';
const Car = {
color,
drive() {
return 'ブーーン!';
},
getColor() {
return this.color;
}
};
とかける。
デフォルト引数
function addOffset(style) {
if (!style) {
style = {};
}
style.offset = '10px';
return style;
}
と書いていた物が
function addOffset(style = {}) {
style.offset = '10px';
return style;
}
と引数に直接デフォルト値を設定できる。
Rest,Spread演算
function unshift(array, a, b, c, d, e) {
return [a, b, c, d, e].concat(array);
}
と書いていた物が
function unshift(array, ...rest) {
return [...rest, ...array];
}
と書けるようになった。
/** スプレッド構文 */
const arr1 = [1,2,3,4,5];
const arr2 = [9,0,7,6,8];
/** 配列の残り */
function unshift(array, ...rest) {
return [...array, ...rest ];
}
console.log(unshift(arr1,6,7,8,9));
/** 配列をコピー */
const arr3 = [...arr1];
console.log(arr3);
/** arr6 = arr3[0]と書いてもarr1[0]が変更されない。 */
/** 配列を結合 */
const arr4 = [...arr1, ...arr2];
console.log(arr4);
分割代入
/** 分割代入 とテンプレート文字列 */
const profile = {
name: 'aaa',
age: 22,
};
const message1 = `私の名前は${profile.name}です。年齢は${profile.age}`
console.log(message1);
/** profileを何回も書かなくて済む */
const { name, age } = profile;
const message2 = `私の名前は${name}です。年齢は${age}`
console.log(message2);
const { name, age } = profile;
と一行でかけるようになった。