"Filling the #{container} with #{l-6ren">
gpt4 book ai didi

coffeescript - 默认函数参数排序

转载 作者:行者123 更新时间:2023-12-03 06:04:55 26 4
gpt4 key购买 nike

通读this ,我开始讨论函数参数的默认值:

fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."

这很好,但后来我尝试了这个:

fill = (container="mug", liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."

alert fill(liquid="juice")

并收到意外警报:“正在用咖啡填充果汁...”。然后我尝试了这个:

fill = (container="mug", liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."

alert fill(null, "juice")

并且成功了。但它并不漂亮。有没有更好的方法,或者这是执行此操作的惯用方法?

最佳答案

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"

关于coffeescript - 默认函数参数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5238398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com