LoginSignup
4
4

More than 5 years have passed since last update.

ES2015の備忘録

Last updated at Posted at 2017-04-23

ES2015の記法、機能のメモ

constとlet

const:再代入しない変数を宣言する時に使用する。上書きされたくないものを代入する。
let: 再代入が必要となる変数を宣言する時に使用する

let number = 1;
const foo = "bar";
foo = "bar2"; //エラー!!!

オブジェクト設定

オブジェクトのプロパティ名が同じ場合、省略できる。

conbst bax = {foo:foo, zoo:zoo};
conbst bax = {foo, zoo}; 

オブジェクトの値に関数を定義するときfunctionを省略できる

const foo = {
  bar(){
    console.log("xxx");
  }
}
foo.bar();

オブジェクトのプロパティ名に変数を利用できる

const foo = "foo";
const bar = {
  [foo + "01"]:"ok"
};
console.log(bar.foo01); //"ok"

アロー関数

ES2015からの関数の表記法。thisの参照先が変わるので注意!

表記の基本形。

関数名 = 引数 => 関数の中身;

functionという単語を省略できる

const f1 = () => "hello";  //const f1 = function() {return "hello";} 
console.log("あいさつ:" + f1()); //あいさつ:hello

引数が一つなら()を省略できる

const f2 = name => "hello:" + name; //const f2 = function(name) {return "hello" + name;}
console.log(f2("世界")); //hello:世界

関数内が一行ならば{}とreturn文を省略できる

//const f3 = function(a,b) {return a + b;}
const f3 = (a,b) => a + b;
console.log("合計値:" + f3(3,4));

引数が複数あるとき

const function = (x, y, z) => {console.log(x, y, z);};

//function:関数名
//(x, y, z) 引数
//console.log(x, y, z); 関数の中身

引数の初期値を設定できる

const foo = (bar = 3) => {
  console.log(bar);
}
foo(4); //4
foo(); //3

スプレッド演算子

  • 可変長な引数を配列として取得できる
const bar = (...arg) => {
  console.log(arg); //1,2,3,4
  console.log(Array.isArray(arg)); //true
};
bar(1,2,3,4);

配列

配列の結合

const foo = [1,2,3];
const bar = [...foo,4,5,6]; //fooの配列内に4,5,6の値を格納する
console.log(bar);

const array = [1,2,...foo,3]; //配列内の好きな位置に配列を入れることができる

filter

配列の中から条件に一致する要素をフィルタリングして、新しい配列として生成する。

例:偶数の値のみを残した配列を生成

const even = value => { 
  return value % 2 == 0; 
}
var array = [1, 2, 3, 4, 5];
var evens = array.filter(even);
console.log(evens); //[2, 4]

map

配列の要素すべてに同じ処理を適用して、新しい配列を生成する。

例:配列内の要素の値を2倍にした配列を新たに生成する

const twice = value => {
  return value * 2;
}

var array = [1,2,3,4];
var arrayTwice = array1.map(twice);
console.log(arrayTwice); //[2, 4, 6, 8]
console.log(array); //[1, 2, 3, 4]
4
4
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
4
4