默认功能参数排序 [英] Default function parameter ordering
本文介绍了默认功能参数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通过这个,我对函数参数的默认值进行了一些比较:
fill =(container,liquid =coffee) - >
用#{liquid}填充#{container} ...
整洁,但我尝试这样:
fill =(container =mug,liquid =coffee) - >
pre>
使用#{liquid}填充#{container} ...
警告填充(liquid =juice)
,并通过
用咖啡填充果汁...
获得了意外的提醒。所以我尝试这样:fill =(container =mug,liquid =coffee) - >
pre>
用#{liquid}填充#{container} ...
警告填充(null,juice)
它工作。这不是很漂亮。
解决方案
是否有更好的方法,或者这是惯用的方法吗? fill =({container,liquid} = {}) - >
container?=mug
liquid?=coffee
用#{liquid}填充#{container} ...
alert fill(liquid:juice,container:glass)
alert fill()
$ b b
fill =(quantity =500 mL,{container,liquid} = {}) - >
container?=mug
liquid?=coffee
#{container}填充#{container} b
$ b警告填充(1L,液体:果汁,容器:玻璃)
警告填充()
警告填充1L 1L,液体:水
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"
这篇关于默认功能参数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文