如何在CoffeeScript生成器中更改分隔符?

时间:2016-02-23 14:17:51

标签: coffeescript

以下代码:

yearsOld = max: 10, ida: 9, tim: 11

ages = for child, age of yearsOld
  "#{child} is #{age}"

将返回:

max is 10, ida is 9, tim is 11

如何让它返回没有逗号的值?像那样:

max is 10 ida is 9 tim is 11

3 个答案:

答案 0 :(得分:1)

<强> c.coffee

yearsOld = max: 10, ida: 9, tim: 11

ages = (input)->
  output=""
  for k,v of input
    output += k + " is " + v + " "
  return output

console.log ages yearsOld

运行

coffee c.coffee
max is 10 ida is 9 tim is 11 

答案 1 :(得分:1)

ages中没有“逗号”。

ages是一个数组,如果您将一个数组写入控制台,则默认行为是使用逗号显示它。如果您不想要逗号,可以使用Array#join生成一个字符串,将值与您想要的任何分隔符分隔开来:

yearsOld = max: 10, ida: 9, tim: 11

ages = for child, age of yearsOld
  "#{child} is #{age}"

agesString = ages.join ' '

console.log agesString

答案 2 :(得分:0)

如果你想要一个&#34;单行&#34;:

<强> c.coffee

yearsOld = max: 10, ida: 9, tim: 11

console.log  (("#{k} is #{v}") for k, v of yearsOld).join(' ')

运行

coffee c.coffee
max is 10 ida is 9 tim is 11 

如果要过滤,例如不包括ida:

console.log ((("#{k} is #{v}") if k != "ida") for k, v of yearsOld ).join(' ').replace('  ', ' ').replace(/^\s/, '')

或仅在10岁以上:

console.log ((("#{k} is #{v}") if v > 10) for k, v of yearsOld ).join(' ').replace('  ', ' ').replace(/^\s/, '')