Javascript TypeError:未定义不是一个对象
2021-03-14
8703
使用某些 Javascript 脚本时出现此错误:TypeError:undefined 不是对象(正在评估“results[j].distance.text”)
尝试按照其他帖子中的建议添加“var results = []”,但没有帮助。
function CalculatedRecommededDistance() {
event.preventDefault();
var origin = document.getElementById('pick_up_address').value;
var destination = document.getElementById('drop_off_address').value;
var geocoder = new google.maps.Geocoder();
var service = new google.maps.DistanceMatrixService();
var results = [];
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false,
avoidFerries: false
}, function(response, status) {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('outputRecommended');
outputDiv.innerHTML = '';
//Display distance recommended value
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
});
}
2个回答
Javascript TypeError: undefined 不是对象
,这意味着您尝试将
undefined
值视为
Object
。(简单来说:尝试从
undefined
值获取数据)
您可以使用
?
安全地忽略此错误。如
results[j]?.distance?.text
。但这不会让您获得预期的结果。因此,首先
console.log(result)
并查看该输出中是否有预期的对象。
w0lf
2021-03-14
在获取结果之前,请检查结果是否具有距离和持续时间属性:
function CalculatedRecommededDistance() {
event.preventDefault();
var origin = document.getElementById('pick_up_address').value;
var destination = document.getElementById('drop_off_address').value;
var geocoder = new google.maps.Geocoder();
var service = new google.maps.DistanceMatrixService();
var results = [];
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false,
avoidFerries: false
}, function(response, status) {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('outputRecommended');
outputDiv.innerHTML = '';
//Display distance recommended value
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
if (result[j].hasownproperty("distance") && result[j].hasownproperty("duartion")){
outputDiv.innerHTML += results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
}
});
}
Belhadjer Samir
2021-03-14