coffee真的很简洁. 但是在函数参数和返回值这里还可以更简洁. 比如规定必须用键值对(对象)作为参数和返回值, 那么小括号和大括号都可以省略了.

IIFE
  • 用do就可以了.
双重循环生成扁平不重复数组
getpointpair= (e)->
#写法一	因为两重循环外层push内层结果, 所以需要flat
	({from: e[x], to: j} for x in [i+1...e.length] for j,i in e).flat()
#写法二 也可以自己弄一个数组作为返回结果
	res=[]
	for j,i in e
		res.push({from: e[x], to: j}) for x in [i+1...e.length]
	res
#和flat等价的写法, 这里xxx是一个数组
[].concat xxx...
循环的步进不为1
for d, i in data by 4 # (var i=0,n=data.length;i<n;i+=4)
if then else
  if d<l then d++	else if da<lus then tp++ else ''
判空运算符
zip = lottery.drawWinner?.address?.zipcode
zip = lottery.drawWinner ?.address ?.zipcode
# 这两个是不一样的. 有空格代表属性, 直接用null判断, 没有空格代表方法, 会用function类型判断
# 20210128, 现在上面两个一致了, 都是直接用null判断
# 但是如果用在if里面必须没有空格
for x in p
		if x.E?
			siteshowinfo["点位"]=true
<>{ if p? then <Boxc text="点" onClick={show type:'point'}/>}</>
对象简写不可以省略大括号
  • CoffeeScript has a shortcut for creating objects when you want the key to be set with a variable of the same name. that the { and } are required for this shorthand.
  • why?
  • CoffeeScript shortcut key value same name. why { }
  • 因为多参数的判断问题. 本来coffee的实现是合理的. 架不住很多人提bug. 作者就修复了这个.
特别要注意<和>
  • 因为jsx的存在, 特别要注意<>, 尤其是<
  • 千万记得前后加空格, 不然很容易出问题.
空格很重要
  • 加空格出问题, 空格在很多时候代表函数调用
p[Q] #p[Q];
p [Q] #p([Q]); p的函数调用
  • 没空格出问题, 因为jsx要用<>, 因为3.a 这个句点可能代表浮点数
if b < bb # 这个是正常的
if b<bb # 这个会引起语法问题
# js里面有类似的浮点数问题
# 参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
77 .toExponential()
# or
77
.toExponential()
# or
;(77).toExponential()
# or
77..toExponential()
# or
77.0.toExponential()
# because 77. === 77.0, no ambiguity
  • 没空格出问题
window.map.remove x for x in k2overlays[key] ?[]
# ?前面这个空格规则很奇怪, 如果没有空格, 那么对于前面的的判断是函数判断. 加了空格才当做null判断
# 这个后续似乎修复了, 前面有写
不可省略的小括号
fs.createReadStream path
.on "error", (err)-> # 这里->之前的err必须有括号, 不然err就是函数名
.pipe res
参考
  • https://coffeescript-cookbook.github.io/chapters/arrays/concatenating-arrays