Actionscript3:变量是否存在?

Jak*_*son 11 variables flash adobe exists actionscript-3

我对Actionscript有点新意,但我无法想出这个.我已就此主题进行了大量搜索,但未找到明确的答案.我尝试了以下人们在网上发布的解决方案,但没有一个能够正常工作.

以下所有解决方案都给出了错误:1120:访问未定义的属性myVariable

建议#1:

try {
     trace(myVariable); }
catch {
     trace("your variable doesn't exist"); }
Run Code Online (Sandbox Code Playgroud)

建议#2:

if (myVariable) {
     trace("your variable exists!!"); }
else {
     trace("it doesn't exist"); }
Run Code Online (Sandbox Code Playgroud)

建议#3:

if ( myVariable == null )
     trace("your variable doesn't exist");
Run Code Online (Sandbox Code Playgroud)

建议#4:

if ( myVariable == undefined )
     trace("your variable doesn't exist");
Run Code Online (Sandbox Code Playgroud)

就像我说的,我发现很多论坛帖子和网上的东西都给出了上述建议说他们会工作,但他们似乎都给了我同样的1120:访问未定义的属性myVariable错误.

顺便说一句,如果你想知道为什么我需要检查变量是否存在,我打算在其URL中将变量传递给SWF,所以我需要确保存在适当的变量并处理代码适当的,如果他们没有被传入.


感谢您的快速答复.仍然没有真正的工作.变量的范围仅在脚本的顶级/根级别.基本上,我启动一个新的flash文件,在第一帧我添加以下操作:

// to check for this.myVariable
if ( this.hasOwnProperty( "myVariable" ) ) {
     trace("myVariable exists");
}
else
{
     //Variable doesn't exist, so declare it now
     trace("declaring variable now...");
     var myVariable = "Default Value";
}

trace(myVariable);
Run Code Online (Sandbox Code Playgroud)

当我运行flash文件时,我得到了这个输出:

myVariable exists
undefined
Run Code Online (Sandbox Code Playgroud)

我在期待这个:

declaring variable now...
Default Value
Run Code Online (Sandbox Code Playgroud)

fen*_*mas 12

LiraNuna的答案肯定是访问加载程序参数的正确方法.但是,要回答如何检查变量是否存在的问题(对于后代),这是通过hasOwnProperty()方法完成的,该方法存在于所有对象上:

// to check for this.myVariable
if ( this.hasOwnProperty( "myVariable" ) ) {
    trace("myVariable exists");
} else {
    //Variable doesn't exist, so declare it now
    trace("declaring variable now...");
    this.myVariable = "Default Value";
}

trace( this.myVariable );
Run Code Online (Sandbox Code Playgroud)

这应该涵盖你的情况.但我不知道有什么方法可以通过直接对变量进行引用来检查变量是否存在.我相信你必须通过它的范围来引用它.


Lir*_*una 5

顺便说一句,如果你想知道为什么我需要检查变量是否存在,我打算在其URL中将变量传递给SWF,所以我需要确保存在适当的变量并处理代码适当的,如果他们没有被传入.

然后你采取了错误的方法.这是正确的方法™来读取和验证SWF参数,以及默认值(如果它们不存在):

private function parameter(name:String, defaultValue:String):String
{
        // Get parameter list
    var paramObj:Object = LoaderInfo(stage.loaderInfo).parameters;

        // Check if parameter exists
    if(paramObj.hasOwnProperty(name) && paramObj[name] != "")
        return paramObj[name];                     
    else
        return defaultValue;
}
Run Code Online (Sandbox Code Playgroud)

警告!由于这是"舞台"属性的中继,因此请使用文档类或之后的代码Event.ADDED_TO_STAGE.