gpt4 book ai didi

javascript - 为什么 JavaScript 控制台说我的变量未定义,即使我在两行之前定义了它?

转载 作者:行者123 更新时间:2023-11-29 17:15:48 25 4
gpt4 key购买 nike

我正在使用 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!");
}

绘图.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);

引用:

关于javascript - 为什么 JavaScript 控制台说我的变量未定义,即使我在两行之前定义了它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18114068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com