我是Java语言的新手,所以如果我在这里缺少一些基本知识,请原谅。我有一些读取JSON文件的代码,应该用每个唯一的年份和该年份出现的次数填充数组。通过控制台测试,我可以看到“ filler”对象都是正确的,但是“ counter”数组仅包含上一年和count的重复项。例如,我要
{Year:1970, Count:3}<br>
{Year:1971, Count:1}<br>
{Year:1973, Count:2}<br>
... <br>
etc. <br>
在循环过程中被打印到控制台,但是
0: {Year: 2015, Count: 1}<br>
1: {Year: 2015, Count: 1}<br>
2: {Year: 2015, Count: 1}<br>
3: {Year: 2015, Count: 1}<br>
4: {Year: 2015, Count: 1}<br>
...<br>
最后打印出来。我认为这可能与.push()
返回数组的方式有关,或者因为我在哪里声明了变量,但我真的不知道。
有人可以告诉我我做错了什么吗?
var cnt = 1;
var counter = [];
var i;
fetch('SomeURL', {
method: 'GET'
})
.then(function(response) {
return response.json();
})
.then(function(json) {
var filler = {};
var current = null;
var years = [];
//Populate Year Array
for (i = 1; i < json.length; i++) {
years[i - 1] = json[i].Year
}
years.sort();
current = years[0];
//If the next entry in the array is different from the previous
//entry add a new object to the counter array
for (i = 0; i < years.length; i++) {
if (years[i] != current) {
current = years[i];
filler["Year"] = current;
filler["Count"] = cnt;
console.log(filler);
counter.push(filler)
cnt = 1;
} else {
cnt++;
}
};
console.log(counter)
});