声明类型为int的可选参数并测试其存在性

时间:2011-08-06 16:30:14

标签: actionscript-3 int optional-parameters

在ActionScript 3中,您可以声明可选参数,如下所示:

function (i:int = 0, s:String = "", o:Object = null):void { }

因此,您可以检查用户是否传递参数s和o,因为您可以测试空字符串或null对象if(s&& o)...

但是你如何允许int真正可选?如果i的所有值都有效,包括0,负整数和正整数怎么办?如果你想强制执行整数(不使用数字?)

,该怎么办?

这里的最佳做法是什么? (...)rest可以工作,但是你不能在运行时强制执行一定数量的参数,也不能用于完成有用的代码?

我正在尝试实现一个边距(top:int,right:int,bottom:int,left:int)方法,该方法允许right,bottom和left是可选的。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用int.MAX_VALUEint.MIN_VALUE。请参阅文档here

答案 1 :(得分:2)

您可以使用NaN检查用户是否设置了参数,但您需要使用Number而不是int。对于像设置边距这样的东西,它可能不会有任何区别,因为它可能不会被称为每秒数千次。

function margin(top:Number, right:Number = NaN, bottom:Number = NaN, left:Number = NaN) {
    // Then here test with isNaN(right), isNaN(bottom), etc.
}

答案 2 :(得分:0)

如果所有可能的int值都有效(即您不能将-1指定为特殊的“未提供”值),那么您将无法使用int数据类型。< / p>

我的建议是这个(根据劳伦特的回答):

将类型定义为Number=NaN,并使用isNaN()测试其存在。

如果用户提供了值,则将值转换为int,否则为其指定默认值。

function margin(top:Number, right:Number = NaN, bottom:Number = NaN, left:Number = NaN) {
    // Then here test with isNaN(right), isNaN(bottom), etc.
    if (isNaN(right))
    {
        right = DEFAULT_MARGIN;    // some default value.

        // Any other logic here...
    }
    else
    {
        // Enforce integer values.
        right = int(right);    // or use Math.floor(right);
    }
}

您还可以使用三元运算符来减少行数:

function margin(top:Number, right:Number = NaN, bottom:Number = NaN, left:Number = NaN) {
    // Then here test with isNaN(right), isNaN(bottom), etc.

    // This is equivalent to the example above:
    right = isNaN(right) ? DEFAULT_MARGIN : int(right);
}
相关问题