您可以通过 cfscript 在函数中执行可选参数吗?
我终于开始用 cfscript 编写东西了,所以我开始编写一些需要的格式化函数。这是一个示例:
Function FormatBoolean(MyBool, Format) {
Switch(Format){
Case "YES/NO":{
If (MyBool eq 1)
Return "YES";
Else
Return "NO";
Break;
}
Default:{
If (MyBool eq 1)
Return "Yes";
Else
Return "";
Break;
}
}
}
我想做的是将 Format 设为可选参数。如果不包含参数,该函数当前仍将运行,但找不到格式,并且 cfparam 似乎未转换为 cfscript。
我是否只需要检查格式是否已定义并给它一个值?或者有更好的方法吗?
谢谢
I am finally getting around to writing stuff in cfscript, and so I am starting with writing some needed formatting functions. Here is an example:
Function FormatBoolean(MyBool, Format) {
Switch(Format){
Case "YES/NO":{
If (MyBool eq 1)
Return "YES";
Else
Return "NO";
Break;
}
Default:{
If (MyBool eq 1)
Return "Yes";
Else
Return "";
Break;
}
}
}
What I would like to do is make Format an optional argument. If you don't include the argument, the function will currently still run, but it won't find format, and it seems that cfparam did not get translated to cfscript.
Will I just have to check if Format is defined and give it a value? Or is there a nicer way of doing this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就我个人而言,我更喜欢为此类参数设置默认值。另外,我对函数进行了一些重构...但未经测试:)
请注意,
(arguments.MyBool EQ 1)
可能会替换为(arguments.MyBool)
,所以它涵盖了所有布尔值。您可能有兴趣使其更可靠,例如(isValid("boolean",arguments.MyBool) AND argument.MyBool)
——这应该允许检查任何值。Personally I prefer to set defaults to this kind of arguments. Also I've refactored function a bit... But not tested :)
Please note that
(arguments.MyBool EQ 1)
may be replaced with(arguments.MyBool)
, so it covers all boolean values. You may be interested to make it more reliable, something like this(isValid("boolean", arguments.MyBool) AND arguments.MyBool)
-- this should allow to check any value at all.传递到函数中的所有变量都可以通过 ARGUMENTS 范围以编程方式访问。您可以像数组一样引用它(因为它确实是数组),以及标准结构键访问(我在下面为
MyBool
参数完成的操作):添加您首选的附加值必要时的数据验证级别。
All variables passed into a function are available to access programmatically via the ARGUMENTS scope. You can refer to it as if it were an array (because it is), as well as standard struct key access (which I've done for you below for the
MyBool
parameter):Add your preferred additional levels of data validation as necessary.