本文介绍了默认函数参数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Reading through this, I came to the bit on default values for function arguments:
fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
That's neat, but then I tried this:
fill = (container="mug", liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
alert fill(liquid="juice")
and got the unexpected alert with "Filling the juice with coffee..."
. So then I tried this:
fill = (container="mug", liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
alert fill(null, "juice")
and it worked. It's not pretty though. Is there a better way, or is this the idiomatic way to do this?
解决方案
fill = ({container, liquid} = {}) ->
container ?= "mug"
liquid ?= "coffee"
"Filling the #{container} with #{liquid}..."
alert fill(liquid: "juice", container: "glass")
alert fill()
fill = (quantity="500 mL", {container, liquid} = {}) ->
container ?= "mug"
liquid ?= "coffee"
"Filling the #{container} with #{quantity} of #{liquid}..."
alert fill("1L", liquid: "juice", container: "glass")
alert fill()
alert fill "1L"
alert fill "1L", liquid: "water"
这篇关于默认函数参数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!