LoginSignup
17
17

More than 5 years have passed since last update.

CoffeeScriptで覚えたい文法

Last updated at Posted at 2015-08-16

ワイ用のメモや

商の整数値

coffee
a // b
js
Math.floor(a / b)

整数化(切り捨て)

coffee
a // 1
js
Math.floor(a)

累乗

coffee
a ** b
js
Math.pow(a, b)

配列の走査

coffee
for value, key in array
   console.log key
   console.log value
js

var i, key, len, value;

for (key = i = 0, len = array.length; i < len; key = ++i) {
  value = array[key];
  console.log(key);
  console.log(value);
}

連想配列の走査

coffee
for key, value of hash
   console.log key
   console.log value
js

var key, value;

for (key in hash) {
  value = hash[key];
  console.log(key);
  console.log(value);
}

配列要素の指定

..は右端を含む
...は右端を含まない
点の数と意味の覚え方
..は「近い」ので「含む」。...は「遠い」ので「含まない」。
@puriketu99談)

coffee
test = [0,1,2,3,4,5,6,7,8]

ika = test[0..3]
miman = test[0...3]

for i in [0..3]
   console.log i
for i in [0...3]
   console.log i
js
var i, ika, j, k, miman, test;

test = [0, 1, 2, 3, 4, 5, 6, 7, 8];

ika = test.slice(0, 4);

miman = test.slice(0, 3);

for (i = j = 0; j <= 3; i = ++j) {
  console.log(i);
}

for (i = k = 0; k < 3; i = ++k) {
  console.log(i);
}

スワップ

coffee
[theBait, theSwitch] = [theSwitch, theBait]
js
ref = [theSwitch, theBait], theBait = ref[0], theSwitch = ref[1];

いらん要素を捨てる

coffee
text = "Every literary critic believes he will
        outwit history and have the last word"
[first, ..., last] = text.split " "
js
var first, last, ref, text;

text = "Every literary critic believes he will outwit history and have the last word";

ref = text.split(" "), first = ref[0], last = ref[ref.length - 1];

比較演算子の連結

coffee
healthy = 200 > cholesterol > 60
js
healthy = (200 > cholesterol && cholesterol > 60);

ヒアドキュメント

"""で囲む
インデント入れてよし

coffee
text = """
       ora
       ora
       ora
       """
js
var text;

text = "ora\nora\nora";
17
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
17