变量未定义,变量范围奇怪

时间:2016-06-24 02:49:58

标签: javascript variables scope

我在.js文件中运行下面的javascript时出现以下错误。

  

未捕获的ReferenceError:未定义startloc

但是我想如果我在脚本的顶部声明变量,那么它们对于它们下面的所有方法都是可见的..我不知道它为什么说没有定义...

var startLoc = new Array();
var endLoc = new Array();


//Map Initialisation
function initMap() {
}

//Marker addon
function addMarker(lattitude, longitude) {
}

// Sets the map on all markers in the array.
function setMapOnAll(map) {
}

//Clear markers on the map
function clearMarkers() {
}

//delete markers array 
function deleteMarkers() {
}

//Plot the markers on the map  
$("document").ready(function(){
    $("#getData").submit(function(event){
        event.preventDefault();
        var reset = 0;
        window.setInterval(function(){
            $.ajax({
                url : "/getVehiclePosition.php",
                type: "POST",
                datatype: "json",
                data: "",
                success: function(data, textStatus, jqXHR)
                {                    
                    var json_obj = $.parseJSON(data);//parse JSON
                    deleteMarkers();

                    for (var i in json_obj) 
                    {
                       if (reset = 0){
                            startloc[i-1] = "X";
                            reset = 1;
                        } else {
                            endLoc[i-1] = "Y";
                            reset = 0;
                        }   

                        console.log(startloc[i-1]);
                        console.log(endloc[i-1]);

                    }

                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    console.error(
                        "The following error occurred: "+
                        textStatus, errorThrown
                    );
                }
            });

        }, 15000);
    });
});

2 个答案:

答案 0 :(得分:1)

错字 - 你用资本宣布它" L"

var startLoc = new Array();

但是使用小写" l"

startloc[i-1] = "X";

应该是

 startLoc[i-1] = "X";

与endLoc的console.log相同:

console.log(endloc[i-1]);

另外 - 你的文件准备也不正确 - 你不需要那里的引号 - 改为:

$(document).ready(function(){

答案 1 :(得分:0)

错误startLocstartloc。尝试纠正

相关问题