npm install -g coffee-script # watch and compile coffee -w --output lib --compile src // coffee -w -c index.coffee
CoffeeScript在編譯時爲每條語句加上;node
CoffeeScript中的註釋採用#npm
target = "world" alert "hello, #{target}" //注意雙引號 alert "hello" + target
object1 = one: 1, two: 2 object2 = one: 1 two: 2 arr1 = [1, 2] arr2 = [ 1, 2 ]
obj = {a:"foo", b:"bar"} {a, b} = obj arr = [1, 2] [a, b] = arr
numbers = [0..9] //兩個或三個點號 numbers[3..5] = [-3,-4,-5] //替換number 3-5的值;能夠是任意個數 my = "my string"[0..1]
arr = ["foo", "bar"] "foo" in arr
for name, i in ["roger", "roderick"] alert "#{i} - Release #{name}"
items = ["ranger", "roderick", "brian"] alert 'ok' for item in items when item is "ranger"
items = [{id: 0, name: "ranger"}, {id: 1, name: "roderick"}, {id: 2, name: "brian"}] result = (item for item in items when item.id is 1) //注意前面有個item;以數組形式返回
sum = (nums) -> nums.reduce(x, y) -> x + y sum 1,2,3 // (function() { var sum; sum = function(nums) { return nums.reduce(x, y)(function() { return x + y; }); }; sum(1, 2, 3); }).call(this);
times = (a = 1, b = 2) -> a * b
CoffeeScript的函數調用能夠不用()語法包圍參數,像ruby同樣跟在函數名後面就能夠,不過這也有時候會帶來問題,特別是沒有參數的調用數組
縮進的格式有時須要當心,好比用多個函數作參數的時候ruby
$(".toggle").toggle -> "on" , -> "off" // (function() { $(".toggle").toggle(function() { return "on"; }, function() { return "off"; }); }).call(this);