简体   繁体   中英

Javascript not properly iterating over array?

So I'm making a little roguelike game in Javascript and have an error with a piece of my rendering code. Not the rendering itself but a little sub-part of it that iterates over an array of objects, checking if any of the objects have coordinates that match the x and y parameters, then returning the object if coordinates match.

Here's the code giving me trouble

Client.Render.checkObjects = function(objects, x, y) {
    for (var a = 0; a < objects.length; a++) {
        if (objects[a].x == x && objects[a].y == y) {
            return objects[a];
        } else {
            return false;
        }
    }
};

I have an array of objects called testSnap.objects which I made like this:

function testObject(x, y) {
    this.x = x;
    this.y = y;
    this.symbol = "a";
};
testSnap.objects.push(new testObject(5,5));
testSnap.objects.push(new testObject(3,5));

I then try

console.log(Client.Render.checkObjects(testSnap.objects, 5, 5));
console.log(Client.Render.checkObjects(testSnap.objects, 3, 5));

Which returns:

Object { x: 5, y: 5, symbol: "a" }
false

It seems objects[a] is never objects[1] ?

You'll only ever return an object if the first object matches. If it doesn't, you're immediately returning false. Try:

Client.Render.checkObjects = function(objects, x, y) {
  for (var a = 0; a < objects.length; a++) {
    if (objects[a].x == x && objects[a].y == y) {
        return objects[a];
    }
  }

  // NOW return false if we never matched
  return false;
};

Your return false statement needs to be after your for loop; otherwise false will be returned when the first object does not match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM