在带有Coffeescription的函数参数中使用哈希

Using the hash in a function argument with Coffeescript

本文关键字:哈希 参数 函数 Coffeescription      更新时间:2023-09-26

目前,我正在使用CoffeeScript,我需要能够将选项传递到参数中,并让它们在函数中运行。

在ruby中,我会做这样的事情:

def some_method(options = {})
  options.each do |key, value|
    puts "the #{key} key has a value of #{value}"
  end
end
some_method(hello: "world", something: "else")

我该如何在CoffeeScript中进行此操作?

您应该查看咖啡文档。

  • 函数和默认参数http://coffeescript.org/#literals
  • 回路http://coffeescript.org/#literals

    对于密钥,obj 的值

开始吧,这很简单:

some_method = (options) ->
  alert "the #{key} key has a value of #{value}" for key, value of options
some_method hello: "World", something: "else"

为了简化从ruby到coffee的转换,您还可以像这样分离for循环:

some_method = (options) ->
  for key, value of options
    alert "the #{key} key has a value of #{value}"
some_method hello: "World", something: "else"