![](/img/trans.png)
[英]Console error saying variable not defined, even though defined in same function
[英]Why is the JavaScript console saying my variable is undefined, even when I defined it two lines before?
我正在使用WebSockets連接到遠程主機,每當我填充realData
並將其傳遞給grapher()
,JavaScript控制台都會告訴我realData
是未定義的。 我嘗試檢查數組中數據的類型,但這似乎很好。 在使用帶有隨機數據的數組之前,我已經調用了grapher()
,並且該調用順利進行了。 但是,使用來自WebSocket的數據,該調用將始終給我“錯誤:未定義realData”。 我不確定為什么會這樣。 這是我使用的代碼:
current.html:
var command = "Hi Scott"
getData();
function getData()
{
console.log("getData is called");
if("WebSocket" in window)
{
var dataCollector = new WebSocket("ws://console.sb2.orbit-lab.org:6100",'binary');
dataCollector.binaryType = "arraybuffer";
console.log(dataCollector.readyState);
dataCollector.onopen = function()
{
//alert("The WebSocket is now open!");
console.log("Ready state in onopen is: " + dataCollector.readyState);
dataCollector.send(command);
console.log(command + " sent");
}
dataCollector.onmessage = function(evt)
{
console.log("onmessage is being called");
var realData = new Uint8Array(evt.data);
console.log(realData);
grapher(realData); //everything up to this point works perfectly.
}
dataCollector.onclose = function()
{
alert("Connection to Server has been closed");
}
return (dataCollector);
}
else
{
alert("Your browser does not support WebSockets!");
}
}
graphing.js:
function grapher(realData)
{
console.log("grapher is called");
setInterval('myGraph(realData);',1000); //This is where the error is. I always get "realData is not defined".
}
function myGraph(realData)
{
/*
for(var i = 0; i < SAarray.length; i++) // Loop which will load the channel data from the SA objects into the data array for graphing.
{
var data[i] = SAarray[i];
}
*/
console.log("myGraph is called");
var bar = new RGraph.Bar('channelStatus', realData);
bar.Set('labels', ['1','2','3','4','5','6','7','8']);
bar.Set('gutter.left', 50);
bar.Set('gutter.bottom', 40);
bar.Set('ymax',100);
bar.Set('ymin',0);
bar.Set('scale.decimals',1);
bar.Set('title','Channel Status');
bar.Set('title.yaxis','Status (1 is on, 0 is off)');
bar.Set('title.xaxis','Channel Number');
bar.Set('title.xaxis.pos',.1);
bar.Set('background.color','white');
bar.Set('colors', ['Gradient(#a33:red)']);
bar.Set('colors', ['red']);
bar.Set('key',['Occupied','Unoccupied']);
bar.getShapeByX(2).Set('colors',barColor(data[0]));
bar.Draw();
}
由於傳遞給setInterval
字符串(作為代碼)在全局范圍內執行,因此realData
參數不可用。 很少有理由將字符串傳遞給setInterval
。 而是使用:
setInterval(function () {
myGraph(realData);
}, 1000);
參考:
嘗試它而不需要評估字符串:
setInterval(function() {
myGraph(realData);
},1000);
任何時候使用setTimeout
或setInterval
,都應該選擇傳遞實際函數而不是字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.