Javascript在原型中循环 请考虑代码: // define the GameObject constructor function var GameObject = function(width, height) { this.x = Math.floor((Math.random() * myCanvasWidth) + 1); this.y = Math.floor((Math.random() * myCanvasHeight) + 1); this.width = width; this.height = height; return this; }; // (re)define the GameObject prototype object GameObject.prototype = { x: 0, y: 0, width: 5, width: 5, draw: function() { myCanvasContext.fillRect(this.x, this.y, this.width, this.height); } };
然后我们可以实例化游戏对象100次Javascript在原型中循环 请考虑代码: // define the GameObject constructor function var GameObject = function(width, height) { this.x = Math.floor((Math.random() * myCanvasWidth) + 1); this.y = Math.floor((Math.random() * myCanvasHeight) + 1); this.width = width; this.height = height; return this; }; // (re)define the GameObject prototype object GameObject.prototype = { x: 0, y: 0, width: 5, width: 5, draw: function() { myCanvasContext.fillRect(this.x, this.y, this.width, this.height); } };,javascript,Javascript,然后我们可以实例化游戏对象100次 var x = 100, arrayOfGameObjects = []; do { arrayOfGameObjects.push(new GameObject(10, 10)); } while(x--); 现在我们有了一个100个游戏对象的数组,它们都共享相同的原型和draw方法的定义,这大大节省了应用程序中的内存 当我们调用draw方法时,它将引用完全相同的函数 var GameLoop = function() { for(
var x = 100,
arrayOfGameObjects = [];
do {
arrayOfGameObjects.push(new GameObject(10, 10));
} while(x--);
现在我们有了一个100个游戏对象的数组,它们都共享相同的原型和draw方法的定义,这大大节省了应用程序中的内存
当我们调用draw方法时,它将引用完全相同的函数
var GameLoop = function() {
for(gameObject in arrayOfGameObjects) {
gameObject.draw(); // this is my problem. Is this correct? gameObject is simply and index who draw() method gets executed
}
};
我的问题是执行方法draw()的最后一行代码。由于gameObject只是一个索引,如何执行draw()方法?该索引不包含任何对象。它只是一个索引,对吗
是一个链接你真的应该在你的
游戏循环中使用以下链接
:
var GameLoop = function() {
for(var i = 0; i < arrayOfGameObjects.length; i++) {
arrayOfGameObjects[i].draw();
}
};
var GameLoop=function(){
对于(变量i=0;i
使用普通的for
循环遍历数组
var GameLoop = function() {
for (var i = 0; i < arrayOfGameObjects.length; i++) {
arrayOfGameObjects[i].draw();
}
};
var GameLoop=function(){
对于(变量i=0;i
实际上,在数组中使用
for in
循环是一种不好的做法,因为这只是获取所需索引的一种迂回的方法。我喜欢jquery$。每个
$.each(arrayOfGameObjects, function(i, gObject) {
gObject.draw();
});
否则,如其他人所述,使用for并使用数组长度进行迭代。var GameLoop=function(){
var GameLoop = function() {
for(var i = 0, len = arrayOfGameObjects.length; i<len; i++) {
gameObject.draw();
}
};
对于(var i=0,len=arrayOfGameObjects.length;iya u是正确的,但由于我在这方面有问题,我需要在特殊情况下获得帮助请参阅我的最后一行代码where draw()方法得到执行,这正确吗,因为var gameObject只保存索引no object draw方法是如何执行的?不正确。在您的特定实例中,您的LOC应该是:arrayOfGameObjects[gameObject].draw()
。我已经放置了一个链接,请查看它。我仍然不理解您的问题。我上面的评论告诉您应该如何。。。