[英]javascript : In For loop pushing the value into the array variable, but values get appended(push) with undefined
if (objJson[0].task.length > 0) {
var Arrayset = [];
var categories = [];
var starts1 = [];
var ends1 = [];
var val1 = [];
var val2 = [];
for (var i = 0; i < objJson[0].task.length; i++) {
var syearval = parseInt(objJson[0].PSDate[i].substr(0, 4));
var smonthval = parseInt(objJson[0].PSDate[i].substr(5, 2));
var sdateval = parseInt(objJson[0].PSDate[i].substr(8, 2));
var eyearval = parseInt(objJson[0].PEDate[i].substr(0, 4));
var emonthval = parseInt(objJson[0].PEDate[i].substr(5, 2));
var edateval = parseInt(objJson[0].PEDate[i].substr(8, 2));
val1=[Date.UTC(syearval, smonthval, sdateval)];
val2= [Date.UTC(eyearval, emonthval, edateval)];
starts1.push(val1[i]);
ends1.push(val2[i]);
Arrayset.push({ name: objJson[0].task[i], completed: objJson[0].taskpercent[i], start:starts1[i], end:ends1[i] });
}
MainLoadChart(Arrayset);
}
}
Declared two array variable starts1 and ends1 .声明了两个数组变量starts1和ends1 。
For loop when i=0当i=0时 for 循环
starts1=[1574035200000] ends1=[1574640000000]开始 1=[1574035200000] 结束 1=[1574640000000]
values get added correctly in the array.值被正确添加到数组中。
same thing, for loop gets iterated (ie) when i=1 etc同样的事情,当i=1等时,for 循环被迭代(即)
starts1=[1574035200000, undefined ] ends1=[1574640000000, undefined ]开始1=[1574035200000,未定义] 结束1=[1574640000000,未定义]
In starts1 and ends1 array undefined gets added in the array.在starts1和ends1数组中未定义被添加到数组中。 I tried in all the ways and i am unable to fix to solve this issue.我尝试了所有方法,但无法解决此问题。
When i = 1当我 = 1
Your val1 will have only 1 value in array same for val2 ie array will have only 1 element您的 val1 在数组中只有 1 个值,与 val2 相同,即数组只有 1 个元素
And you are pushing index value which will be undefined
并且您正在推送undefined
索引值
How about怎么样
Instaed of代替的
starts1.push(val1[i]);
ends1.push(val2[i]);
Use用
starts1.push(val1[0]);
ends1.push(val2[0]);
There is a problem with assignment of val1
and val2
. val1
和val2
分配存在问题。 You are repeatedly assigning a new array with 1 item to it, that's why there is value at index 0(when i=0) and undefined
for index 1, 2,3 .. and so on.您重复分配一个包含 1 个项目的新数组,这就是为什么索引 0(当 i=0 时)有值而索引 1, 2,3 .. 等undefined
的原因。
You can actually skip this declaration & assignments of val1, val2
and directly push values to array.您实际上可以跳过val1, val2
此声明和赋值val1, val2
并直接将值推送到数组。
//val1=[Date.UTC(syearval, smonthval, sdateval)];
//val2= [Date.UTC(eyearval, emonthval, edateval)];
starts1.push(Date.UTC(syearval, smonthval, sdateval));
ends1.push(Date.UTC(eyearval, emonthval, edateval));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.