Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 循环对象法_Javascript_Arrays_Loops_Object_Methods - Fatal编程技术网

Javascript 循环对象法

Javascript 循环对象法,javascript,arrays,loops,object,methods,Javascript,Arrays,Loops,Object,Methods,我试图用一个循环同时调用一个objects方法。 我会创建一个游戏,让一群敌人同时移动 我创建了一个对象战士 function Warrior(x, y) { // Coordinates x, y this.x = x; this.y = y; this.character = $('<div class="enemy"></div>'); // Inserting the div inside #map

我试图用一个循环同时调用一个objects方法。 我会创建一个游戏,让一群敌人同时移动

我创建了一个对象战士

    function Warrior(x, y) {

    // Coordinates x, y 

    this.x = x;
    this.y = y;

    this.character = $('<div class="enemy"></div>');

    // Inserting the div inside #map
    this.character.appendTo('#map'); 


    // assigning x and y parameters

    this.character.css({        

        marginLeft: x + 'px',
        marginTop: y + 'px'

    });

    // walk method that move the div

    this.walk = function() {

        // Moving div 10px to the right
        this.character.css('left', "+=10");

    }

    }

    var enemies = new Array();
    enemies[0] = new Warrior(0, 0);
    enemies[1] = new Warrior(10, 20);
    enemies[2] = new Warrior(60, 80);

    for(var i=0;i<enemies.length;i++) {
        setInterval(function(){enemies[i].walk()}, 1000);
    }
我已经创建了一个数组

同时我尝试调用walk方法

但什么也没发生。我希望div同时移动

谢谢

基于问题

您可能希望通过值将参数传递给setInterval:


如果不传递参数,则循环运行时x变量会发生变化,因此所有函数都将在x=2时调用,因为数组中有3个元素

您有两个主要问题,其中:

CSS不允许像javascript那样进行编程修改。在javascript中修改值,然后在CSS中设置:

this.walk = function() {
    var current = parseInt(this.character.css('left')),
        stepped = current + 10;
    this.character.css('left', stepped);
}
您的循环在var i上创建一个闭包,该闭包只声明一次,因此相同的值将在函数之间共享。您可以让函数获取一个参数,并在setInterval调用中提供它:

setIntervalfunctionindex{/*…*/},1000,i; 或者,您可以将循环置于interval函数中:

setInterval(function() {
    for (var i = 0; i < enemies.length; i++) {
         enemies[i].walk();
    }
});
您可能还需要重新考虑walk函数是否应该直接修改CSS。您已经忘记了代码中的x和y坐标属性。也许你应该有一个修改这些坐标的行走方法,以及一个根据精灵当前坐标更新精灵位置的绘制功能。

你有没有测试过在任何敌人身上行走,它会移动?如果没有,那么问题就不在循环中。
setInterval(function() {
    for (var i = 0; i < enemies.length; i++) {
         enemies[i].walk();
    }
});