coffeeScript学习01
2015-03-25 11:22
120 查看
安装
这里使用node.jsnpm install -g coffee-script # watch and compile coffee -w --output lib --compile src // coffee -w -c index.coffee
语法
CoffeeScript不是JavaScript的超集,不能在CoffeeScript程序中写JavaScript代码格式
CoffeeScript在编译时为每条语句加上;CoffeeScript中的注释采用#
作用域
会自动添加变量声明‘var’,放到作用域的顶部赋值
字符串可以用类ruby的语法内嵌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
数组
数组的操作引入了来自ruby的Range概念,并且可以将字符串完全作为数组操作numbers = [0..9] //两个或三个点号 numbers[3..5] = [-3,-4,-5] //替换number 3-5的值;可以是任意个数 my = "my string"[0..1]
判断一个值是否在数组内
arr = ["foo", "bar"] "foo" in arr
for..in语法
for name, i in ["roger", "roderick"] alert "#{i} - Release #{name}"
过滤器when
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;以数组形式返回
流程控制
函数
CoffeeScript对JavaScript的函数做了很大的简化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);
->来代替function; 注意前面空一格
参数列表放在->的前边,且可省略
取消了函数声明,只能将函数作为值定义
在CoffeeScript中,任何语句都是表达式(除了break和continue),都有返回值,因此像ruby一样,不需要显式return
CoffeeScript的函数可以有默认参数
times = (a = 1, b = 2) -> a * b
CoffeeScript的函数调用可以不用()语法包围参数,像ruby一样跟在函数名后面就可以,不过这也有时候会带来问题,特别是没有参数的调用
缩进的格式有时需要小心,比如用多个函数做参数的时候
$(".toggle").toggle -> "on" , -> "off" // (function() { $(".toggle").toggle(function() { return "on"; }, function() { return "off"; }); }).call(this);
相关文章推荐
- 学习笔记01-关于extern和ifndef-def
- ROS系统学习01 - 安装ROS系统
- 接口测试学习 -01
- hdwiki 学习笔记 01
- 01分数规划:学习总结
- (01)Entity Framework 6.1 学习系列1--概况、安装
- 教程学习 01-Building a RESTful Web Service 学习笔记
- CSS学习笔记01-块元素和内联元素.html
- 前端学习-CSS-01
- python数据结构学习笔记-2016-11-30-01-堆
- SSH与SSM学习之SSH整合01——SSH整合原理和导包
- Android 学习 笔记_01
- Hibernate学习-01:Hibernate框架的概述
- play_java框架学习01
- Effective C++学习笔记-01
- iBATIS学习01:iBATIS概览+iBATIS十分钟快速上手操练
- PHP学习散记 2012_01_07(MySQL)
- 编程小白的第一本 python 入门书 学习笔记01 第二章 安装Python环境
- iOS FFmpeg入门学习01
- day67_Redis学习笔记_01