Javascript 使用循环使用值填充变量,然后检索特定的;“时刻”;这个变量的
抱歉,标题有点模糊。我搜索了网络和stackoverflow,但我有点(实际上有点)困惑 让我解释一下: 我正在使用javascript和Phaser框架。我用一个精灵创建了一个变量,但是用for循环我动态地改变了纹理并给它自定义值。像这样:Javascript 使用循环使用值填充变量,然后检索特定的;“时刻”;这个变量的,javascript,loops,phaser-framework,Javascript,Loops,Phaser Framework,抱歉,标题有点模糊。我搜索了网络和stackoverflow,但我有点(实际上有点)困惑 让我解释一下: 我正在使用javascript和Phaser框架。我用一个精灵创建了一个变量,但是用for循环我动态地改变了纹理并给它自定义值。像这样: for (var x = 0; x < some value; x++) { this.myVar = this.game.add.sprite(this.world.width * .5, 480, 'gui_image
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
};
}
到目前为止没有问题
---问题从这里开始---
如果我对myVar执行console.log()并检查其customParams,我将获得循环的最后一个值。(也就是说,如果循环从0运行到5,我将从console.log(myVar.customParams.somethingarayposition)
获得4)
我想做的并且让我困惑的是:我想创建一个临时变量,它将表示,例如,myVar.customParams.somethingArrayPosition的位置2
比如:
myComparingFunction: function(item) {
if(item.customParams.clicked){
//do something
}
}
var temp = myVar.customParams.somethingArrayPosition[2]...
所以我可以说temp.visible=false代码>并使其消失。。。现在,我只得到最后一个精灵消失,或者得到值,而不是说该值指向该精灵,隐藏它
干杯,如果这是一个愚蠢的问题,我现在真的很困惑…所以我认为最简单的解决方案是创建数组作为Phaser.Game
实例的属性,然后将精灵添加到其中
我见过,但相关代码的一个示例是:
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;
},
create:function(){
this.spriteCollection=[];
对于(变量x=0;x<3;x++){
this.ball=this.game.add.sprite(this.game.world.centerX,5+30*x,'ball');
此.ball.anchor.setTo(0.5,0);
这个.spriteCollection.push(这个.ball);
}
//将返回所有三个精灵,您可以通过它们查看它们是否具有正确的位置。
console.log(this.spriteCollection);
//如图所示。
console.log(this.spriteCollection[0].position);
//取消注释以查看此操作。
this.spriteCollection[1].visible=false;
},
您仍然可以继续向添加的每个精灵添加一个customParams
,但不依赖于单个精灵数组属性;如果你console.log
我相信你会看到它在每个循环中被覆盖,因为this.myVar=this.game.add.sprite(this.world.width*.5480,'gui_images',''代码>正在重置此。myVar
谢谢你,詹姆斯!这是我必须习惯的事情。。。是的,我倾向于依赖单个精灵属性,是的,精灵本身被覆盖,但我仍然可以调用和查看单个属性并使用它们。我有一棵有6个苹果的苹果树。它们都是相同的精灵,就像我上面的代码一样。每个都有一个x值,因此它会递增。在函数上,如果我执行类似于invisible:function(item){if(item.customParams.value==2){item.visible=false;}}}
的操作,它将工作。。。但在大多数情况下,这是一个更好的解决方案!谢谢很乐意帮忙!祝你在相位器方面好运。:)