[英]Key value paired array element returns “undefined” error while it is assigned the value in given index javascript
I need four key/value paired arrays for my code and I decrement the value for each array based on conditions. 我的代码需要四个键/值配对数组,并根据条件递减每个数组的值。 In checking if the given value is bigger than 0 I randomly get "undefined" error in each of the four arrays and I do not know how to fix this problem 在检查给定值是否大于0时,我在四个数组中的每一个中随机获得“未定义”错误,并且我不知道如何解决此问题
Here is my code: 这是我的代码:
Asett=[
"A" ,
"B",
"C"
]
var Bset = [
"D",
"E",
"F"
];
var Cset = [
"G" ,
"H",
"I"
];
var Dset = [
"J",
"K",
"L"
];
var cSets = [];
var vSets=[];
var dSets=[];
var fSets=[];
function initiate(){ //this function initiates the given arrays with defined elements and value equal to 10
for (var iv=0;iv<3;iv++){
cSets.push({
key: Asett[iv],
rem:10
})
}
for (var iv=0;iv<3;iv++){
vSets.push({
key: Bset[iv],
rem:10
})
}
for (var iv=0;iv<3;iv++){
dSets.push({
key: Cset[iv],
rem:10
})
}
for (var iv=0;iv<3;iv++){
fSets.push({
key: Dset[iv],
rem:10
})
}
}
initiate();
generateList(cSets,vSets,dSets,fSets);
function generateList(cSets,vSets,dSets,fSets){
var j=0;
var k=0;
var l=0;
var m=0;
var taskL = []; // create an empty array
var f=0;
for (var i=0; i<27;i++){
j=getRndInteger(0,2);
k=getRndInteger(0,2);
l=getRndInteger(0,2);
m=getRndInteger(0,2);
var combinations="";
while (cSets[j].rem<=0) // I get cSets[j] undefined error
{
j=(j % 3) +1;
}
combinations+=comSets[j].key+",";
comSets[j].rem--;
while (vSets[k].rem<=0) //I get vSets[k] undefined error
{
k=(k % 3) +1;
}
combinations+=vSets[k].key+",";
vSets[k].rem--;
while (dSets[l].rem<=0) //I get dSets[l] undefined error
{
l=(l % 3) +1;
}
combinations+=changeSets[l].key+",";
changeSets[l].rem--;
while (fSets[m].rem<=0) //I get fSets[m] undefined error
{
m=(m % 3) +1;
}
combinations+=fSets[m].key+",";
fSets[m].rem--;
taskL[f++]=combinations;
}
}
In this code I expect my taskL array to get the combinations however I randomly recieve undefined error for each of the given sets (cSets, vSets, dSets and fSets) even though they are assigned value. 在这段代码中,我希望我的taskL数组能够得到组合,但是即使给它们分配了值,我也会随机收到每个给定集合(cSet,vSet,dSet和fSet)的未定义错误。 Any help would be appreciated 任何帮助,将不胜感激
You have to change all of j=(j % 3) +1; 您必须更改所有j =(j%3)+1; these into j=(j+1) % 3 This way when your j is 2, it will be +1 and it will be 3 then %3 it will be 0 so you would not get out of bound exception. 将它们转换为j =(j + 1)%3这样,当您的j为2时,它将为+1,它将为3,然后%3将为0,因此您不会超出范围的异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.