ページ

2014年1月28日火曜日

Ruby On Rails アプリケーション作成 5 - CoffeeScript -

CoffeeScriptお勉強


ドットインストールで勉強させて頂きながら、公式サイトのインタラクティブツールで
javascriptに変換される様子を見ながら勉強。

■ javasctipt変換前
# comment
###
 aaa
###
message = "hello world"
if message.length > 1
  alert message

s = """this is pen.
it the end"""

name = "taguchi"

alert "hi, #{name}, #{s}, #{15/3}"

###
配列、連想配列
###
a0 = [1, 2, 3, 4]
a1 = [
     1, 5, 8
     2, 4, 2
     ]

a3 = 
     "sato":
        "sales" : 200
        "cost"  : 80
     "sasaki":
        "sales" : 250
        "cost"  : 40

a4 = [1..5]
a5 = [1...5]

###
if文
###
signal = "red"

if signal == "red"
  alert "stop!"
else if signal == "green"
  alert "go"

###
比較演算子
is (===) isnt(!==)
not(!)
and(&&)
or(||)
###

x = 20

alert "true" if 10 < x < 30

###
switch
###

signal = "red"

switch signal
  when "red"
    alert "stop!"
  when "greed"
    alert "go"
  else
    alert "caution"

###
存在チェック
###

alert "ok!" if name?

###
for loop
###
for i in [0..3]
  alert i

a = ["a", "b", "c"]

for i, index in a
 alert "#{index}:#{i}"

###
連想配列のループ
###
sales = 
  "tanaka": 100
  "taguchi" : 200
  "sasaki": 300

for key, value of sales
  alert "#{key}:#{value}"
  

###
関数
###

hello = (s="aaa") ->
  alert "hello #{s}"

hello("ddd")
hello()

###
返り値
###

sum = (a, b) ->
  a + b


■ 変換後
/*
 aaa
*/

var a, a0, a1, a3, a4, a5, hello, i, index, key, message, name, s, sales, signal, sum, value, x, _i, _j, _len;

message = "hello world";

if (message.length > 1) {
  alert(message);
}

s = "this is pen.\nit the end";

name = "taguchi";

alert("hi, " + name + ", " + s + ", " + (15 / 3));

/*
配列、連想配列
*/


a0 = [1, 2, 3, 4];

a1 = [1, 5, 8, 2, 4, 2];

a3 = {
  "sato": {
    "sales": 200,
    "cost": 80
  },
  "sasaki": {
    "sales": 250,
    "cost": 40
  }
};

a4 = [1, 2, 3, 4, 5];

a5 = [1, 2, 3, 4];

/*
if文
*/


signal = "red";

if (signal === "red") {
  alert("stop!");
} else if (signal === "green") {
  alert("go");
}

/*
比較演算子
is (===) isnt(!==)
not(!)
and(&&)
or(||)
*/


x = 20;

if ((10 < x && x < 30)) {
  alert("true");
}

/*
switch
*/


signal = "red";

switch (signal) {
  case "red":
    alert("stop!");
    break;
  case "greed":
    alert("go");
    break;
  default:
    alert("caution");
}

/*
存在チェック
*/


if (name != null) {
  alert("ok!");
}

/*
for loop
*/


for (i = _i = 0; _i <= 3; i = ++_i) {
  alert(i);
}

a = ["a", "b", "c"];

for (index = _j = 0, _len = a.length; _j < _len; index = ++_j) {
  i = a[index];
  alert("" + index + ":" + i);
}

/*
連想配列のループ
*/


sales = {
  "tanaka": 100,
  "taguchi": 200,
  "sasaki": 300
};

for (key in sales) {
  value = sales[key];
  alert("" + key + ":" + value);
}

/*
関数
*/


hello = function(s) {
  if (s == null) {
    s = "aaa";
  }
  return alert("hello " + s);
};

hello("ddd");

hello();

/*
返り値
*/


sum = function(a, b) {
  return a + b;
};

0 件のコメント:

コメントを投稿