0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ES6の新機能 [随時更新予定]

Last updated at Posted at 2019-04-24

① テンプレートリテラル

テンプレートリテラルを使うことで正しく早くコードを書くことができるようになりました。


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));

出力結果

スクリーンショット 2019-04-24 17.26.13.png

③アロー関数

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で追加されたアロー関数を使うと少ない行で綺麗にコードが書けるようになります。

スクリーンショット 2019-04-24 17.51.11.png

引数が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]

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?