count变量不迭代for循环

时间:2013-11-13 22:24:25

标签: javascript

嘿我试图增加这个变量num_pass的计数,每次我们通过if语句成功循环。它虽然不断吐出0或1。

我尝试将变量放在许多不同的地方并在不同的地方声明它但仍然没有成功。

function pickup()
{   
var num_pass = 0;
var i;
var array = PASSENGERS[i];
for (var i = 0; i < PASSENGERS.length; i++)
{
    // get location of passengers
    var lat = PASSENGERS[i].placemark.getGeometry().getLatitude();
    var long = PASSENGERS[i].placemark.getGeometry().getLongitude();

    // calculate distance of passengers to bus
    var distance = shuttle.distance(lat, long);

    // screen for freshman

    // if passengers are close enough
    if (distance <= 15)
    {
        // if there is room on the bus
        // iterate through all the seats
        var j;
        var array = shuttle.seats;

  for (j = 0;j < shuttle.seats.length;j++)
        {

            // if a seat is empty
            if (shuttle.seats[j] == null && PASSENGERS[i].house != "Thayer Hall") 
            {          

                // remove picture from the 3-D map
                var features = earth.getFeatures();
                features.removeChild(PASSENGERS[i].placemark);

                // remove marker from the 2-D map
                PASSENGERS[i].marker.setMap(null);

                // remove 2-D map attribute of passenger
                PASSENGERS[i].marker = null;

                // add to the shuttle
                shuttle.seats[j] = PASSENGERS[i];

                // update the chart
                chart();

                $('#announcements').html("Passenger picked up!"); 
                $('#announcements').html("Score: " + score);

                num_pass++;                    


            }
            console.log(shuttle.seats[j]); 

        }


    }

    else if (num_pass > 9)
    {
        $('#announcements').html("no room on bus");
    }
    else if (distance > 15)
    {
        $('#announcements').html("no passenger nearby");
    }
}

1 个答案:

答案 0 :(得分:-1)

这应该有效:

for (j = 0; j < shuttle.seats.length; j++) {

  // if a seat is empty
  if (shuttle.seats[j] == null && PASSENGERS[i].house != "Thayer Hall") {

    // remove picture from the 3-D map
    var features = earth.getFeatures();
    features.removeChild(PASSENGERS[i].placemark);

    // remove marker from the 2-D map
    PASSENGERS[i].marker.setMap(null);

    // remove 2-D map attribute of passenger
    PASSENGERS[i].marker = null;

    // add to the shuttle
    shuttle.seats[j] = PASSENGERS[i];

    // update the chart
    chart();

    $('#announcements').html("Passenger picked up!");
    $('#announcements').html("Score: " + score);

    num_pass++;

  // @lukpaw explanation: Code below was unnecessary
  //}
  console.log(shuttle.seats[j]);

  // @lukpaw explanation: Code below was unnecessary
  //}
  }
  else if (num_pass > 9) {
    $('#announcements').html("no room on bus");
  } else if (distance > 15) {
    $('#announcements').html("no passenger nearby");
  }
}