CoffeeScript攻略3.8:字串插值

CoffeeScript Cookbook發表於2011-11-27

問題

你想建立一個字串,讓它包含表現某個CoffeeScript變數的文字。

方案

使用CoffeeScript中類似Ruby的字串插值,而不是JavaScript的字串拼接。

插值:

muppet = "Beeker"
favorite = "My favorite muppet is #{muppet}!"

# => "My favorite muppet is Beeker!"
square = (x) -> x * x
message = "The square of 7 is #{square 7}."

# => "The square of 7 is 49."

討論

CoffeeScript的插值與Ruby類似,多數表示式都可以用在#{...}插值結構中。

CoffeeScript支援在插值結構中放入多個有副作用的表示式,但建議大家不要這樣做。因為只有表示式的最後一個值會被插入。

# 可以這樣做,但不要這樣做。否則,你會瘋掉。
square = (x) -> x * x
muppet = "Beeker"
message = "The square of 10 is #{muppet='Animal'; square 10}. Oh, and your favorite muppet is now #{muppet}."

# => "The square of 10 is 100. Oh, and your favorite muppet is now Animal."

enter image description here

相關文章