views:

39

answers:

1

Hi,

To begin with, I have a database that holds map data for a game I am creating. A script on my page uses JSON to retrieve a certain amount of that data from the database and store it in an array.

When the data is retrieved it goes through a function that finds out how many individual tiles are used in that particular area. Here is the code:

var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4){
        var map = JSON.parse(xmlhttp.responseText);
        var mapTiles = new Array;
        for(var count = 0; count < map.length; count ++){
            if(map[count]){
                if(map[count]['tile'] in mapTiles == false){
                    mapTiles.push(map[count]['tile']);
                }
            }
        }
        alert(mapTiles);
    }
}

For each time the script finds a tile number that isn't already in the mapTiles array it adds it to it.

Currently, the script is fetching 1024 records that all but one contain the tile value of '1' the other of which contains the tile value of '2'. This means that when I alert the mapTiles array it should display "1, 2" but instead it displays "1, 1, 2". So there is a slight error in the script but I cannot find it.

+3  A: 

The in operator checks to see if the object has the named property or contains an element at the array index. In your case, the check is always false because the first time, there are no elements and so it returns false. When mapTiles contains 1 it's in the zeroth position and thus the check returns false. When you check for 2, the last element is in the first position and thus it returns false. You need to iterate through the array and check for the value of the element, rather than use the in operator.

 function contains( obj, aray )
 {
      for (var i = 0, len = aray.length, isIn = false; i < len && !isIn; ++i) {
          isIn = aray[i] === obj;
      }
      return isIn;
 }


 ...
 if(!contains(map[count]['tile'],mapFiles)){
     mapTiles.push(map[count]['tile']);
 }
tvanfosson
Thanks for the good answer! +1
Stanni