ITeye博客

CoffeeScript notes: write less do more

lingceng · 2013-07-26 10:36 · Javascrpt · web · Web前端 · Markdown

The Little Book on CoffeeScript official site

CoffeeScript is a little language that compiles down to JavaScript. The syntax is inspired by Ruby and Python, and implements many features from those two languages.

I found some amazing features when using CoffeeScript on my project. Here I have some examples. wonderful idioms of array and object Array#forEach() Array#map() Array#filter() are latest features introduced in ECMAScript 5, CoffeeScript have compatible idioms to implement them.


# forEach function
myFunction(item) for item in array

# map function
result = (item.name for item in array)

# filter and map
result = (item for item in array when item.name is "test")

Demo: convert objects array to values array using coffeescript online demo


# convert object to array in order
	objs = [ {
			sn: "dfjjk"
			project: "fly"
			department: "origin"
			feelings :"well"
		},{
			sn: "dfjjk"
			project: "fly"
			department: "origin"
			feelings :"well"
		}]
		
	order = ["project", "sn",  "feelings", "department"]

	result =  
		for obj in objs
			for name in order 
				obj[name] 
				
	# or in simple way	
	#result = ((obj[name] for name in order ) for obj in objs)
				
	console.log result
	for r in result
				$("body").append r + "<br/>"

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。