CoffeeScript
文法で見落としているところがないかドットインストールをざっと見て再確認した。
配列内包
sum = 0 total = (sum += i for i in [0..9] by 2) console.log total # => [0, 2, 6, 12, 20] # ループごとのsumの値を要素とする配列が返される
while
i = 0 sum = 0 total = while i < 10 sum += i i++ console.log total # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # whileブロックの中で最後に評価された値を要素とする配列が返される
分割代入
# 複数の変数にまとめて代入できる # Rubyっぽいけど括弧が邪魔 [a, b, c] = [1, 5, 10] # 数値の入れ替え x = 10 y = 20 [x, y] = [y, x] # 複数の値を関数から返すように書ける # これもRubyっぽい results = (x) -> [x, x**2, x**3] [a, b, c] = results 5 # オブジェクトから値を取り出すことも可能 user = name: 'butcher' score: 52 email: 't@d.com' {name, email} = user
class
# コンストラクタの引数を @____ とすると勝手に代入してくれる class User constructor: (@name) ->
存在演算子
# 変数の存在チェック # チェック結果により処理を分ける rs = if x? then "found" else "not found" # xがあればx, なければ20を代入 y = x ? 20 # オブジェクトのチェック user = name: 'tagi' # プロパティの存在チェック # 無ければTypeErrorになるが以下のように書けばundefinedが返る a = user.score?.first # メソッドの存在チェック b = user.sayhi?()