默认功能参数排序

编程入门 行业动态 更新时间:2024-10-09 22:18:22
本文介绍了默认功能参数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

通过这个,我对函数参数的默认值进行了一些比较:

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"

更多推荐

默认功能参数排序

本文发布于:2023-06-02 19:31:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/457410.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!