使用循环使用值填充变量,然后检索该变量的特定 "moment"

Populate a variable with values using a loop and than retrieve a specific "moment" of that variable

抱歉标题有点模糊。我搜索了网络和计算器,但我有点(实际上不止一点)困惑。

让我解释一下: 我正在使用 javascript 和 Phaser 框架。我正在创建一个带有 sprite 的单个变量,但使用 for 循环我动态更改纹理并为其赋予自定义值。像这样:

    for (var x = 0; x < some value; x++) {

         this.myVar = this.game.add.sprite(this.world.width * .5, 480, 'gui_images', '');

          this.myVar.customParams = {
               clicked: false,
               labelColor: 'labelBlue_small',
               somethingArray: this.arraySomething[x],
               somethingArrayPosition: x
             };
}

到目前为止,我只需要访问给定值或与给定值进行比较。所以我会使用一个函数并做类似的事情:

myComparingFunction: function(item) {
    if(item.customParams.clicked){
        //do something
    }
}

目前没有问题。

--- 问题从这里开始 ---

如果我对 myVar 执行 console.log() 并检查其 customParams,我将获得循环的最后一个值。 (即如果循环从 0 < 5 运行,我将从 console.log(myVar.customParams.somethingArrayPosition) 得到 4)

我想做但让我感到困惑的是:我想创建一个临时变量来表示,例如,myVar.customParams.somethingArrayPosition...

的位置 2

类似于:

var temp = myVar.customParams.somethingArrayPosition[2]...

所以我可以说 temp.visible = false; 让它消失...现在我只能让最后一个精灵消失,或者得到值而不是说那个值是指那个精灵的方式,隐藏它!

如果这是一个愚蠢的问题,请干杯并抱歉,我现在真的很困惑...

所以我认为最简单的解决方案是将数组创建为 Phaser.Game 实例的 属性,然后将精灵添加到其中。

我有 created a JSFiddle that showcases this,但相关代码的示例是:

create: function() { 
    this.spriteCollection = [];

    for (var x = 0; x < 3; x++) {
        this.ball = this.game.add.sprite(this.game.world.centerX, 5 + 30 * x, 'ball');
      this.ball.anchor.setTo(0.5, 0);
      this.spriteCollection.push(this.ball);
    }
    // Will return all three sprites, which you can go through and see have the correct position.
    console.log(this.spriteCollection);
    // As shown here.
    console.log(this.spriteCollection[0].position);
    // Uncomment to see this in action.
    this.spriteCollection[1].visible = false;
},

您仍然可以继续为您添加的每个精灵添加一个customParams,但不要依赖于单个精灵数组属性;如果你 console.log 我相信你会看到它在每个循环中都被覆盖了,因为 this.myVar = this.game.add.sprite(this.world.width * .5, 480, 'gui_images', ''); 正在重置 this.myVar.