我声明了一个带有空数组值的变量 names ,然后在函数内部使用它来分配返回值,然后我想在函数之外使用它,但是在函数外面这个变量仍然是空的。 请解释我做错了什么。
handleUpdateInputBusinessName = (searchText) => {
var names = [];
var displaySuggestions = function(predictions, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
predictions.forEach(function(prediction) {
let name = prediction.description;
names.push(name);
});
console.log('names_in:', names); // valid predictions from Google Maps Service
return names;
};
console.log('names_out:', names); // []
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: searchText, types: '(cities)'
}, displaySuggestions);
答案 0 :(得分:0)
这是简化版本:
a = [];
var b = () => {
a.push(1);
console.log('inside:', a)
};
console.log('outside:', a);
b();

"外面"控制台日志在调用displaySuggestions
函数之前运行,因此数据尚未填充在数组中。
答案 1 :(得分:0)
你必须使用js匿名函数语法来增加下面名称数组的范围是代码。
handleUpdateInputBusinessName = (searchText) => {
var names = [];
var displaySuggestions = (predictions, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
predictions.forEach((prediction) => {
let name = prediction.description;
names.push(name);
});
console.log('names_in:', names); // valid predictions from Google Maps Service
return names;
};
console.log('names_out:', names); // []
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: searchText, types: '(cities)'
}, displaySuggestions);
希望这会好起来。