① テンプレートリテラル
テンプレートリテラルを使うことで正しく早くコードを書くことができるようになりました。
let firstName = 'John';
let lastName = 'Smith';
const yearOfBirth = 1990;
function calcAge(year) {
return 2016 - year;
}
// ES5
console.log('this is ' + firstName + ' ' + lastName + '. He was born in ' + yearOfBirth + ' . Today, he is' + calcAge(yearOfBirth) + 'years old.');
// ES6 ( テンプレートリテラル )
console.log(`this is ${firstName} ${lastName}. He was born in ${yearOfBirth}. Today he is ${calcAge(yearOfBirth)} years old. `);
② 文字列で追加された新しいメソッド
let firstName = 'John';
let lastName = 'Smith';
const yearOfBirth = 1990;
function calcAge(year) {
return 2016 - year;
}
// ES5
console.log('this is ' + firstName + ' ' + lastName + '. He was born in ' + yearOfBirth + ' . Today, he is' + calcAge(yearOfBirth) + 'years old.');
// ES6 ( テンプレートリテラル )
console.log(`this is ${firstName} ${lastName}. He was born in ${yearOfBirth}. Today he is ${calcAge(yearOfBirth)} years old. `);
// 新しく加わった文字列のメソッド
const n = `${firstName} ${lastName}`;
console.log(n.startsWith('j'));
console.log(n.endsWith('Sm'));
console.log(n.includes('oh'));
console.log('${firstName}',repeat(5));
出力結果
③アロー関数
3つの方法があります。
1, 最初は1つの引数と1行のコードが置かれ最も簡単な形式。
2,別の引数を追加するとかっこを使用すること
3,複数のコード行を追加すると末尾に中括弧とreturnキーワードを使用する必要があること。
例文
私たちは2つの出生年の配列を持っており、これらの年のそれぞれの年齢を計算する
const years = [1990, 1965, 1982, 1937];
// ES5
var age5 = years.map(function(el) {
return 2016 - el;
});
console.log(ages5);
// ES6
const ages6 = years.map(el => 2016 - el);
console.log(ages6);
出力結果
ES6で追加されたアロー関数を使うと少ない行で綺麗にコードが書けるようになります。
引数が2つ以上ある場合は、実際にかっこを指定する必要がある。その例を書いてみます。
const years = [1990, 1965, 1982, 1937];
// ES6
let ages6 = years.map(el => 2016 - el);
console.log(ages6);
ages6 = years.map((el, index) => `Age element ${index + 1}: ${2016 - el}. `);
console.log(ages6);
勉強になる記事
(https://qiita.com/raccy/items/487e62a253d65cc9fee6)[本当にvarは駄目な子なのか?]
(JavaScript初級者のためのコーディングガイド)[https://qiita.com/raccy/items/bf590d3c10c3f1a2846b#_reference-910e146d28f2c4d8f5f5]