1
3

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でできること覚書

Posted at

Javascript ES6 Cheatsheet - the best of JS ES6
https://www.youtube.com/watch?v=AfWYO8t7ed4

:arrow_up: こちらに載っていたコードの写経のようなものです。
なんとなく何やっているのかを見出しとして書いていますが、不適切な可能性がありますので コードを読んで理解してください。:bow:

トランスパイラ

babeljs.io を使おう(traceurってのもあるよ)

ES6

プロパティを別な変数に切り出す

オブジェクトから

var foo = {
  bar: 1,
  baz: 2
};

// before
var bar = foo.bar;
var baz = foo.baz;

// after
var { bar, baz } = foo;

配列から

var tenses = ["me", "you", "he"];
var [firstPerson, secondPerson, thirdPerson] = tenses;

Promise と併用

Promise.all([promise1, promise2]).then(function(results) {
  var [ results1, results2 ] = results;
});

// 引数の時点で展開させることもできる
Promise.all([promise1, promise2]).then(function([results1, results2]) {

});

宣言済みの変数を挿入する

var foo = 2;

var obj = {
  bar: 1,
  foo
};
var name = "will";
var age = 34;

// before
some.method({
  name: name,
  age: age
})

// after
some.method({ name, age });

オブジェクトのキー名の [] の中で文字列を展開できる

var name = "will";
var obj = {
  ["name" + name]: "some value"
}
obj["name"+name] = "some value" // これもOK

引数にオブジェクトを使う(?)

元コード

function calcBmi(weight, height, max, callback) {
  var bmi = weight / Math.pow(height, 2);
  if (bmi > max) {
    console.log("you're overweight");
  }
  if (callback) {
    callback(bmi);
  }
}
calcBmi(weight, height, 25);
calcBmi(weight, height, null, function() {});

引数をオブジェクト化

function calcBmi({ weight, height, max, callback }) { // options.weightとかやらなくて済む

初期値

function calcBmi({ weight, height, max = 25, callback }) {

順番を気にしなくてよい

function calcBmi({ height, weight, max = 25, callback }) { // weightとheightを逆にした

ラベル貼れる

function calcBmi({ weight: w, height: h, max = 25, callback }) {

必要な引数だけ使える

calcBmi(weight, height, max: 25); // callbackをundefinedに
calcBmi(weight, height, callback: function() {}); // maxをundefinedに

Template Strings

var name = "will";
var thing = "party";

// before
var greet = "hi, my name is " + name + "and I like to " + thing + ".";
// after
var greet = `hi, my name ${name} and I like to ${thing}!`;

後半: https://www.youtube.com/watch?v=LmL0Gh193M0 (そのうちこっちも訳す)

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?