LoginSignup
29
11

More than 5 years have passed since last update.

【テンプレートリテラル】と【オブジェクトリテラル】を覚えたら「ちょっと」いい感じにコードが書けた!

Posted at

概要

【テンプレートリテラル】【オブジェクトリテラル】を覚えて「ちょっと」いい感じにコードが書けるようになったので、早速アウトプットします!

テンプレートリテラル

バッククウォート`~`で囲む。シングルクォーテーション'~'じゃないよ。
極めたい人はこちらの記事を参照

const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() + 1;
const week = today.getDay();
const day = today.getDate();
const yobi =['','','','','','','']

//es5
console.log("現在は"+year+""+month+""+day+""+yobi[week]+"曜日です。"); //現在は2019年1月30日水曜日です。

//es6
console.log(`現在は${year}${month}${day+1}${yobi[week+1]}曜日です。`); //現在は2019年1月31日木曜日です。
  • 毎回文字列と変数の間に+を書かなくて済む
  • 文字を書く際に"~"をつけなくて良い
  • 変数や計算式は${~}のなかにを入れることで表現できる

オブジェクトリテラル

たくさん書き方があるらしいんですけど、とりあえず2つご紹介
オブジェクトリテラルマスターになりたい人はこちらから

オブジェクトのkeyとvalueが同じ名前の場合1回書くだけで良い

return {
        //es5
        inventory: inventory

        //es6
        inventory
 }

オブジェクトのvalueがfunctionの場合「: function」を省略可

return {
        //es5
        inventoryValue: function(){
            return this.inventory.reduce((sum,dvd) => sum += dvd.price,0);
        },
        priceForTitle: function(title){
            return this.inventory.find(dvd => dvd.title === title).price;
        }

        //es6
        inventoryValue(){
            return this.inventory.reduce((sum,dvd) => sum += dvd.price,0);
        },
        priceForTitle(title){
            return this.inventory.find(dvd => dvd.title === title).price;
        }
}
29
11
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
29
11