本文介绍了默认功能参数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通过这个,我对函数参数的默认值进行了一些比较:
fill =(container,liquid =coffee) - > 用#{liquid}填充#{container} ...整洁,但我尝试这样:
fill =(container =mug,liquid =coffee) - > 使用#{liquid}填充#{container} ... 警告填充(liquid =juice) pre>,并通过用咖啡填充果汁...获得了意外的提醒。所以我尝试这样:
fill =(container =mug,liquid =coffee) - > 用#{liquid}填充#{container} ... 警告填充(null,juice) pre>它工作。这不是很漂亮。
解决方案是否有更好的方法,或者这是惯用的方法吗? 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"
更多推荐
默认功能参数排序
发布评论