coffeescript1: coffeescript coffeescript。coffeescript。coffeescript。Examples Hello WordLinuxOS...

19
coffeescript #coffeescrip t

Transcript of coffeescript1: coffeescript coffeescript。coffeescript。coffeescript。Examples Hello WordLinuxOS...

coffeescript

#coffeescrip

t

1

1: coffeescript 2

2

Examples 2

Hello WordLinuxOS X 2

2: ProConCoffeescript 3

Examples 3

3

3

3

3

3: 4

Examples 4

4

4: 5

Examples 5

5

5

5

5: 6

Examples 6

6

1 - 6

2 - 6

6: 7

Examples 7

7

1 - .map 7

2 - 7

7

1 - .filter 7

2 - 7

7

8

1 - .concat 8

2 - splats 8

3 - .concat 8

8

7: 9

Examples 9

ifif / thenif / else 9

10

8: 12

Examples 12

12

12

12

12

9: 13

Examples 13

13

13

10: 15

Examples 15

15

15

16

You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: coffeescript

It is an unofficial and free coffeescript ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official coffeescript.

The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners.

Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to [email protected]

https://riptutorial.com/zh-TW/home 1

1: coffeescript

coffeescript。

coffeescript。coffeescript。

Examples

Hello WordLinuxOS X

CoffeeScriptJavaScript。CoffeeScriptJavaScript。

npmCoffeeScript

$ mkdir coffee && cd coffee $ npm install -g coffee-script

-gCoffeeScriptCLI。-g

$ mkdir coffee && cd coffee $ npm install coffee-script

helloword.coffeeCoffeeScript。

console.log 'Hello word!'

CoffeeScript。CoffeeScript

$ coffee helloword.coffee

CoffeeScript

$ ./node_modules/coffee-script/bin/coffee helloword.coffee

Hello word!

coffeescript https://riptutorial.com/zh-TW/coffeescript/topic/4233/coffeescript

https://riptutorial.com/zh-TW/home 2

2: ProConCoffeescript

Examples

CoffeeScript。 CoffeeScriptJavaScript。CoffeeScript;{}}。

CoffeeScript“monkey”。

animals = ["dog", "cat", "monkey", "squirrel"] for item in animals when item isnt "monkey" console.log item

CoffeeScript

var animals, i, item, len; animals = ["dog", "cat", "monkey", "squirrel"]; for (i = 0, len = animals.length; i < len; i++) { item = animals[i]; if (item !== "monkey") { console.log(item); } }

JavaScript

dog cat squirrel

CoffeeScript

"Hello, #{user}, how are you today?"

JavaScript

"Hello, " + user + ", how are you today?";

ProConCoffeescript https://riptutorial.com/zh-TW/coffeescript/topic/6278/proconcoffeescript

https://riptutorial.com/zh-TW/home 3

3:

Examples

# creates a function with no arguments, which returns 3 get_three = () -> return 3 # same as above get_three = -> 3 # creates a function with arguments add_three = (num) -> num + 3 # multiple arguments, etc. add = (a, b) -> a + b

https://riptutorial.com/zh-TW/coffeescript/topic/5723/

https://riptutorial.com/zh-TW/home 4

4:

Examples

container = "cup" liquid = "coffee" string = "Filling the #{container} with #{liquid}..."

- - Filling the cup with coffee...

Coffee-script

sentence = "#{ 22 / 7 } is a decent approximation of π"

。。

html = """ <strong> cup of coffeescript </strong> """

CoffeeScript。。。

mobyDick = "Call me Ishmael. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world..."

https://riptutorial.com/zh-TW/coffeescript/topic/5062/

https://riptutorial.com/zh-TW/home 5

5:

Examples

110console.log。

1 -

for x in [1..10] console.log x

2 -

console.log x for x in [1..10]

https://riptutorial.com/zh-TW/coffeescript/topic/6006/

https://riptutorial.com/zh-TW/home 6

6:

Examples

theUsers = [ {id: 1, username: 'john'} {id: 2, username: 'lexy'} {id: 3, username: 'pete'} ]

['john', 'lexy', 'pete']

1 - .map

theUsernames = theUsers.map (user) -> user.username

2 -

theUsernames = (user.username for user in theUsers)

theUsers = [ {id: 1, username: 'john'} {id: 2, username: 'lexy'} {id: 3, username: 'pete'} ]

id2

[{id: 3, username: 'pete'}]

1 - .filter

filteredUsers = theUsers.filter (user) -> user.id >= 2

2 -

filteredUsers = (user for user in theUsers when user.id >= 2)

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

numbers[0..2][1, 2, 3]•numbers[3...-2][3, 4, 5, 6] numbers[3...-2] [3, 4, 5, 6]•numbers[-2..][8, 9]•

https://riptutorial.com/zh-TW/home 7

numbers[..][1, 2, 3, 4, 5, 6, 7, 8, 9]•

3..6[3, 4, 5, 6] 3,4,5,6 [3, 4, 5, 6] 3 ... 6[3, 4, 5] -

numbers[3..6] = [-3, -4, -5, -6]

[1, 2, -3, -4, -5, -6, 7, 8, 9]

fruits = ['Broccoli', 'Carrots'] spices = ['Thyme', 'Cinnamon']

ingredients = ['Broccoli', 'Carrots', 'Thyme', 'Cinnamon']

1 - .concat

ingredients = fruits.concat spices

2 - splats

ingredients = [fruits..., spices...]

3 - .concat

arrayOfArrays = [[1], [2,3], [4]] [].concat.apply([], arrayOfArrays) # [1, 2, 3, 4]

Array“comprehensions”......

...for...

[express,_] = (require x for x in ['express','underscore'])

“”...

console.log (x.nme for x in [{nme:'Chad',rnk:99}, {nme:'Raul', rnk:9}])

[ 'Chad', 'Raul' ]

( ) 。“”。

https://riptutorial.com/zh-TW/coffeescript/topic/4459/

https://riptutorial.com/zh-TW/home 8

7:

Examples

ifif / thenif / else

if。true 。

counter = 10 if counter is 10 console.log 'This will be executed!'

ifelse。if else。

counter = 9 if counter is 10 console.log 'This will not be executed...' else console.log '... but this one will!'

ifelse。true。

if counter is 10 console.log 'I counted to 10' else if counter is 9 console.log 'I counted to 9' else if counter < 7 console.log 'Not to 7 yet' else console.log 'I lost count'

ifunless 。if unlessfalse。

counter = 10 unless counter is 10 console.log 'This will not be executed!

if then。

if counter is 10 then console.log 'Counter is 10'

Ruby-like

console.log 'Counter is 10' if counter is 10

if / then / else。thenif。else。

https://riptutorial.com/zh-TW/home 9

outcome = if counter is 10 then 'Done counting!' else 'Still counting'

TL; DRCoffeeScriptswitchwhenelse。 then 。break 。 switch。

CoffeeScript switch。ififtruefalse switch -

CoffeeScriptswitchswitch 。when 。

switch name when "Alice" # Code here will run when name is Alice callAlice() when "Bob" # Code here will run when name is Bob giveBobSandwich()

casethen

livesLeft = 2 switch livesLeft when 3 then fullHealth() when 2 then healthAt 2 when 1 then healthAt 1 when 0 then playerDie()

livesLeft = 2 switch livesLeft when 3 then fullHealth() when 2 then healthAt 2 when 1 healthAt 1 alert "Warning! Health low!" when 0 then playerDie()

functoin

indexOfAnswer = 0 switch indexOfAnswer + 1 when 1 then console.log "The answer is the 1st item" when 2 then console.log "The answer is the 2nd item" when 3 then console.log "The answer is the 3rd item"

switch password when "password", "123456", "letmein" then console.log "Wrong!" when "openpoppyseed" then console.log "Close, but no cigar." when "opensesame" then console.log "You got it!"

。 CoffeeScriptelse

switch password when "password", "123456", "letmein" then console.log "Wrong!" when "openpoppyseed" then console.log "Close, but no cigar." when "opensesame" then console.log "You got it!"

https://riptutorial.com/zh-TW/home 10

else console.log "Not even close..."

else casethen。

switch

switch day when "Mon" then go work when "Tue" then go relax when "Thu" then go iceFishing when "Fri", "Sat" if day is bingoDay go bingo go dancing when "Sun" then go church else go work

switch fullName when myFullName() then alert "Doppelgänger detected" when presidentFirstName + " " + presidentLastName alert "Get down Mr. president!" callSecretService() when "Joey Bonzo" then alert "Joey Bonzo everybody"

CoffeeScript switch。switch。

address = switch company when "Apple" then "One Infinite Loop" when "Google" then "1600 Amphitheatre Parkway" when "ACME" if isReal "31918 Hayman St" else "Unknown desert location" else lookUpAddress company

。return。

if / else。

score = 76 grade = switch when score < 60 then 'F' when score < 70 then 'D' when score < 80 then 'C' when score < 90 then 'B' else 'A'

grade = switch truetrue。break s。

https://riptutorial.com/zh-TW/coffeescript/topic/4317/

https://riptutorial.com/zh-TW/home 11

8:

Examples

CoffeeScript。

# Swap [x, y] = [y, x]

person = name: "Duder von Broheim" age: 27 address: "123 Fake St" phoneNumber: "867-5309" {name, age, address, phoneNumber} = person

CoffeeScript。

。。

drawRect = ({x, y, width, height}) -> # here you can use the passed parameters # color will not be visible here! myRectangle = x: 10 y: 10 width: 20 height: 20 color: 'blue' drawRect myRectangle

printTopThree = ([first, second, third]) -> # here you can use the passed parameters # 'Scrooge McDuck' will not be visible here! ranking = ['Huey', 'Dewey', 'Louie', 'Scrooge McDuck'] printTopThree ranking

array = [1, 2, 3, 4] [first] = array # 1 [..., last] = array # 4 [first, middle..., last] = array # first is 1, middle is [2, 3], last is 4

https://riptutorial.com/zh-TW/coffeescript/topic/4461/

https://riptutorial.com/zh-TW/home 12

9:

Examples

CoffeeScript?null 。

1.nullundefined 。

alert "Hello CoffeeScript!" if myVar?

javascript

if (typeof myVar !== "undefined" && myVar !== null) { alert("Hello CoffeeScript!"); }

2.

language = favoriteLanguage ? "coffeescript"

javascript

language = typeof favoriteLanguage !== "undefined" && favoriteLanguage !== null ? favoriteLanguage : "coffeescript";

3.

.?.TypeError 。

firstName = user?.profile?.firstname

javascript

firstName = typeof user !== "undefined" && user !== null ? (ref = user.profile) != null ? ref.firstname() : void 0 : void 0;

undefined

CoffeeScript JavaScript

is == ===

isnt != !==

not !

and &&

https://riptutorial.com/zh-TW/home 13

CoffeeScript JavaScript

or ||

true yes on true

false no off false

@ this this

of in

in

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

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

a %% b (a % b + b) % b

https://riptutorial.com/zh-TW/coffeescript/topic/4915/

https://riptutorial.com/zh-TW/home 14

10:

Examples

CoffeeScript。

class Animal constructor: (@name) -> move: (meters) -> alert @name + " moved #{meters}m." class Snake extends Animal move: -> alert "Slithering..." super 5 class Horse extends Animal move: -> alert "Galloping..." super 45 sam = new Snake "Sammy the Python" tom = new Horse "Tommy the Palomino" sam.move() tom.move()

4

...1. Sammy the Python500。2. ......3. 45。4.

::。

String::dasherize = -> this.replace /_/g, "-"

dasherize。。

https://riptutorial.com/zh-TW/coffeescript/topic/5158/

https://riptutorial.com/zh-TW/home 15

S. No

Contributors

1 coffeescript Artisan72, b3by, Badacadabra, Community, Kevin Chavez

2 ProConCoffeescript Vyren

3 Kevin Chavez

4 Max Dudzinski, Molske

5 Vyren

6 4444, Alex Gray, fracz, fzzle, Molske

7 b3by, c0d3rman, Molske, Vyren

8 b3by, Daniel X Moore

9 Deepak Mahakale, fzzle, Molske

10 Molske

https://riptutorial.com/zh-TW/home 16