coffeescript

2018-02-24 15:18 更新

X分鐘速成Y

其中 Y=coffeescript

源代碼下載:?coffeescript-cn.coffee

CoffeeScript是逐句編譯為JavaScript的一種小型語言,且沒有運(yùn)行時(shí)的解釋器。 作為JavaScript的替代品之一,CoffeeScript旨在編譯人類可讀、美觀優(yōu)雅且速度不輸原生的代碼, 且編譯后的代碼可以在任何JavaScript運(yùn)行時(shí)正確運(yùn)行。

參閱?CoffeeScript官方網(wǎng)站以獲取CoffeeScript的完整教程。

# CoffeeScript是一種很潮的編程語言,
# 它緊隨眾多現(xiàn)代編程語言的趨勢(shì)。
# 因此正如Ruby和Python,CoffeeScript使用井號(hào)標(biāo)記注釋。

###
大段落注釋以此為例,可以被直接編譯為 '/ *' 和 '* /' 包裹的JavaScript代碼。

在繼續(xù)之前你需要了解JavaScript的基本概念。

示例中 => 后為編譯后的JavaScript代碼
###

# 賦值:
number   = 42 #=> var number = 42;
opposite = true #=> var opposite = true;

# 條件:
number = -42 if opposite #=> if(opposite) { number = -42; }

# 函數(shù):
square = (x) -> x * x #=> var square = function(x) { return x * x; }

fill = (container, liquid = "coffee") ->
  "Filling the #{container} with #{liquid}..."
#=>var fill;
#
#fill = function(container, liquid) {
#  if (liquid == null) {
#    liquid = "coffee";
#  }
#  return "Filling the " + container + " with " + liquid + "...";
#};

# 區(qū)間:
list = [1..5] #=> var list = [1, 2, 3, 4, 5];

# 對(duì)象:
math =
  root:   Math.sqrt
  square: square
  cube:   (x) -> x * square x
#=> var math = {
#  "root": Math.sqrt,
#  "square": square,
#  "cube": function(x) { return x * square(x); }
#}

# Splats:
race = (winner, runners...) ->
  print winner, runners
#=>race = function() {
#  var runners, winner;
#  winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
#  return print(winner, runners);
#};

# 存在判斷:
alert "I knew it!" if elvis?
#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }

# 數(shù)組推導(dǎo):
cubes = (math.cube num for num in list) 
#=>cubes = (function() {
#   var _i, _len, _results;
#   _results = [];
#   for (_i = 0, _len = list.length; _i < _len; _i++) {
#       num = list[_i];
#       _results.push(math.cube(num));
#   }
#   return _results;
#  })();

foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
#=>foods = ['broccoli', 'spinach', 'chocolate'];
#
#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
#  food = foods[_k];
#  if (food !== 'chocolate') {
#    eat(food);
#  }
#}
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)