我相信我缺少关于数组寿命的重要信息。请考虑以下几行代码,这些代码根据我的要求返回有关数组长度的不同信息。
附近搜索中的最后一个if语句返回restStops数组的预期长度,而最后一行(for循环之外)返回0作为同一数组的长度。 为什么它们返回有关数组长度的不同信息?
我已经了解了Is the length of an array cached?中的数组缓存,但是我仍然不清楚为什么我的数组没有读到附近的搜索区域之外。
let routesMap = $.extend(google.maps, {}); // extends the Google maps object to enable optionary parameters.
let mapOptions = {
center: new routesMap.LatLng(-37.813611, 144.963056),
mapTypeId: routesMap.MapTypeId.ROADMAP,
zoomControlOptions: {
style: routesMap.ZoomControlStyle.SMALL,
position: routesMap.ControlPosition.RIGHT_BOTTOM
},
zoom: 11
};
let map = new routesMap.Map($("#map-canvas")[0], mapOptions);
let placesService = new routesMap.places.PlacesService(map);
let fraction = Math.round((992304 / 1000) / (5 * 80)); // fraction is a value representing how many stops there should be on a given route leg based on driving time and speed. (992304 meters (distance between two cities) / 1000 meters to get the distance in metric miles) / (5 hours of driving * speed of 80 km/h)
let restStops = []; // array of all suggested rest stops found in the nearby search.
for (let m = 1; m <= fraction; m++) {
// polyline is calculated somewhere else and represents the drawn route between the two cities. It's not essential for this problem, hence omitted from this example.
// GetPointAtDistance is derived from the library epolys.js and uses the starting point of the polyline as its origin for calculation.
let restStopLatLng = polyline.GetPointAtDistance(m * 5 * 80 * 1000); // 5 hours of driving * speed of 80 km/h * 1000 to get the distance in meters.
let searchRequest = {
location: restStopLatLng,
radius: 10000, // 10000 meters.
types: ['campground']
};
// make the nearby search request
placesService.nearbySearch(searchRequest, function (searchResponse, status) {
if (status == routesMap.places.PlacesServiceStatus.OK) {
// create a batch of suggested rest stops to choose from.
for (let restLocation in searchResponse) {
restStops.push(searchResponse[restLocation].geometry.location);
}
} else if (status != routesMap.places.PlacesServiceStatus.ZERO_RESULTS) {
console.log('Request failed: ' + status);
}
// only show the length information when all batches are loaded into restStops.
if (m == fraction) {
console.log("Number of suggested rest stops along the road: " + restStops.length);
}
});
}
console.log("Number of suggested rest stops along the road: " + restStops.length);