2

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]?

2
  • 2
    checkObjects returns false on the first iteration, before it ever gets to objects[1] Commented May 15, 2014 at 14:53
  • Yep, that's the issue. return will cancel your iteration. Well explained question TBF Commented May 15, 2014 at 14:53

2 Answers 2

7

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;
};
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.