我想使用Array.find而不是$ .each,所以一旦找到结果就停止循环,但我无法找出返回邮政编码的正确语法。
navigator.geolocation.getCurrentPosition(function (position) {
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': latLng
}, function (results, status) {
var searchAddressComponents = results[0].address_components;
var zipcode = "";
//searchAddressComponents.find(function() {
//});
/* function isZipcode() {
if(results[0].address_components.types[0]=="postal_code"){
zipcode = element.short_name;
}
}*/
//THIS WORKS BUT WANT TO USE ARRAY.FIND to return Zipcode
$.each(searchAddressComponents, function(){
if(this.types[0]=="postal_code"){
zipcode = this.short_name;
}
});
}); //END OF GEOCODER
});
答案 0 :(得分:2)
有很多方法可以给这只猫上皮。但是,如果您想使用Array#find
,请按以下方式进行操作:
zipcode = searchAddressComponents.find(component => component.types[0] == "postal_code").short_name;

对于ES6之前,功能如下
zipcode = searchAddressComponents.find(function (component) {
return component.types[0] == "postal_code";
}).short_name;
答案 1 :(得分:1)
这应该有效(假设您可以访问ES6语法,例如箭头函数):
const zipcode = searchAddressComponents.find(
component => component.types[0] === 'postal_code'
).short_name;