20. 20
HOW - 基本文法
# 条件分岐 if
if a = ‘apple’
3
else if a = ‘orange’
1
else
0
if 0 < a < 5
‘a is between 0 and 5’
# この書き方も可
a = [1, 3, 5]
x = 3
if x in a
‘x is in a’
# この書き方も可
if x isnt ‘good’
‘unhappy’
# 等価チェックは
# == != ではなく
# is isnt を使おう
21. 21
HOW - 基本文法
# 条件分岐 switch when
flag = "K"
switch flag
when 'M'
then console.log " 明
治 "
when 'T'
then console.log " 大
正 "
else
console.log “ 慶応?”
# switch when then else
# を使う
# then を省略して
# インデントにすることも可
switch flag
when 'M'
console.log “ 明治”
# 各 when の最後に
# break は不要
22. 22
HOW - 基本文法
# ループ for
a = [1, 3, 5]
for ele in a
console.log ele
# 配列には in で
for ele in [0..10]
console.log ele
# 範囲は [first..last]
で
p = {
name: ‘goto’,
favorite: ‘apple’
}
for k, v of p
console.log [k, v]
# オブジェクトには of で
23. 23
HOW - 基本文法
# ループ while
i = 0
while on
console.log i
i++
if i > 3
break
# こちらもインデントで
# 後置書式
a = 1 if true
b = 0.5
b++ while 12 / b < 3
# if for while が使用可
28. 28
HOW - クラス
# クラス定義
class Dog
constructor: (name) ->
this.name = name
# class キーワードで定義
# もちろんインデント
# constructor は
# コンストラクタ
# インスタンス生成
d1 = new Dog(‘Pochi’)
# new クラス名 で
# インスタンス生成
# new 時に constroctor
の
# メソッドが呼ばれる
console.log d1.name
# そのまま
# プロパティアクセス可
29. 29
HOW - クラス
# this. の別の書き方
class Dog
constructor: (name) ->
@name = name
# 現在のオブジェクトの
# プロパティ指定は
# this. 以外に
# @... が使用可
# constructor の省略書式
class Dog
constructor: (@name) ->
# constructor の引数に
# @ 始まりにすると
# @... = ...
# が自動的に実行される
30. 30
HOW - クラス
# クラスメソッド
class Dog
@clsmethod: () -> 1
# クラスメソッドは
# @... で定義する
p = console.log
p Dog.clsmethod # => 1
# 継承
class Dog extends Wolf
# 継承は extends で
34. 34
HOW - その他もろもろ
# true と false の
# バリエーション
# 1 yes no
# 2 on off
# yes on
# ともに true と同じ
# no off
# ともに false と同じ
# 文字列への式の組み込み
“3 + 4 = #{3 + 4}”
# Ruby と同じく
# “” の中の #{} の中は
# 評価される
35. 35
HOW - その他もろもろ
# 内包表記
a = [1, 2, 3]
a_squared =
(x * x for x in a)
# => [1, 4, 9]
# Ruby の map 的なことも
# 1 行で書ける!
a = [0..20]
a7 =
(x for x in a
when x % 7 is 0)
# => [0, 7, 14]
# ( when の前は改行な
し)
# Ruby の select 的なこ
と
# も 1 行で書ける!!
36. 36
HOW - その他もろもろ
# 内包表記つづき
s =
java: 1
ruby: 2
coffee: 3
pair =
([k, v] for k, v of s)
# オブジェクトも
# もちろん回せる
a = [1, 2, 3]
a_squared = for x in a
x * x
# => [1, 4, 9]
# もっと
# 気持ち悪い書き方もできる