我在使用此 JavaScript 代码时遇到问题,(tracking_data) 的第二个警报会抛出“未定义”,就像变量被删除或清除一样,但我没有看到代码的任何部分执行此操作。我希望你能帮我解决这个问题。问候。
var track_id = ''; // Name/ID of the exercise
var watch_id = null; // ID of the geolocation
var tracking_data = []; // Array containing GPS position objects
$("#startTracking_start").live('click', function () {
// Start tracking the User
watch_id = navigator.geolocation.watchPosition(
// Success
function (position) {
tracking_data.push(position);
alert(tracking_data);
},
// Error
function (error) {
console.log(error);
},
// Settings
{frequency: 3000, enableHighAccuracy: true });
// Tidy up the UI
track_id = $("#track_id").val();
$("#track_id").hide();
$("#startTracking_status").html("Tracking workout: <strong>" + track_id + "</strong>");
});
$("#startTracking_stop").live('click', function(){
alert(tracking_data);
// Stop tracking the user
navigator.geolocation.clearWatch(watch_id);
// Save the tracking data
window.localStorage.setItem(track_id, JSON.stringify(tracking_data));
// Reset watch_id and tracking_data
var watch_id = null;
var tracking_data = null;
// Tidy up the UI
$("#track_id").val("").show();
$("#startTracking_status").html("Stopped tracking workout: <strong>" + track_id + " </strong>");
});
最佳答案
由于提升,所有 var 声明都被移动到其封闭函数的顶部。换句话说,您正在重写函数内的 tracking_data
。
从 var tracking_data = null;
(在函数内部)更改为 tracking_data = null;
将解决您的问题。
下面的示例重现了此行为:
var v1 = 'hello';
(function(){
console.log(v1); //prints hello
v1 = 'hi';
console.log(v1); //prints hi
})()
。
var v2 = 'hello';
(function(){
console.log(v2); //prints undefined. Due to hoisting the var v2 was overriden inside this scope.
var v2 = 'hi';
console.log(v2); //prints hi
})()
关于Javascript 全局数组未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17626918/