从数组空值到浏览器刷新的 Javascript 变量

Javascript variable from array null value until browser refresh

本文关键字:Javascript 变量 刷新 浏览器 数组 空值      更新时间:2023-09-26

希望有人能阐明这一点。 我正在从逗号分隔的 cookie(例如 1,2,3,4,5)中获取值,将其设置为变量。 一切都很好,直到我尝试访问数组中设置的变量,这些变量为空,直到我刷新浏览器。有什么想法吗?

//Setting ExampleVar Cookie
var ExampleVar = null;
var ExampleVar = readCookie('SomeCookie');
if (ExampleVar == null) {
createCookie('SomeCookie',ValuesVariable,365)//create cookie if null
}
var ExampleVar = null;
var ExampleVar = readCookie('CookieGoesHere');//e.g. 1,2,3,4,5
document.write (ExampleVar);//Prints out 1,2,3,4,5 as it should
var myArr = new Array(); 
var myArr = ExampleVar.split(",");
for(var i=0;i<myArr.length;i++){  
    document.write("Array Index " + i + " = " + myArr[i] + "<br />");//prints null until     browser is refreshed
}  
var Foo = myArr[0];//set to Null until browser is refreshed
var Bar = myArr[1];//set to Null until browser is refreshed

您没有填充数组。 它不应该打印任何东西。

var ExampleVar = readCookie('CookieGoesHere');//e.g. 1,2,3,4,5
var myArr = ExampleVar.split(',');

应该工作