我使用forEach()
循环,在其中我修改了之前声明的(关联)数组。
但无论我尝试什么,似乎改变只发生在if/else
内,并在其外被忽略。
我做错了什么?
var referer = [],
r,
result = [
{ _id: 'http://www.url1.com/video/agenda-du-mois-de-juin-6/', count: 3 },
{ _id: 'http://www.url2.com/video/reaction-de-bertrand-rocheron/', count: 3 },
{ _id: 'http://www.url1.com/video/victoire-du-rac-basket-3/', count: 30 },
{ _id: 'http://www.url3.com/embed-3194.html', count: 3 },
{ _id: 'http://www.url2.com/categorie-video/actu/page/10/', count: 9 },
{ _id: 'http://www.url1.com/video/agenda-de-septembre/', count: 4 },
{ _id: 'http://www.url2.com/video/le-journal-du-mardi-18-mars/', count: 8 },
{ _id: 'http://www.url3.com/video/programme-du-6-avril-2012/', count: 1 }
];
console.log(result);
result.forEach(function (element, i) {
//Get domain
r = element._id.replace('http://', '').replace('www.', '').split('/')[0];
console.log(r);
//If it exist
if (referer[r]) {
//Add data in it
console.log('\tADD : ' + r);
referer[r].y = referer[r].y + element.count;
} else {
//Else create it
console.log('\tCREATE : ' + r);
referer[r] = {name: r, y: element.count};
}
//Why do this is still empty...?
console.log('\tTOTAL : ' + JSON.stringify(referer));
});
//...When I need to use it here?
console.log('result: ' + JSON.stringify(referer));
输出:
url1.com
CREATE : url1.com
TOTAL : []
url2.com
CREATE : url2.com
TOTAL : []
url1.com
ADD : url1.com
TOTAL : []
url3.com
CREATE : url3.com
TOTAL : []
url2.com
ADD : url2.com
TOTAL : []
url1.com
ADD : url1.com
TOTAL : []
url2.com
ADD : url2.com
TOTAL : []
url3.com
ADD : url3.com
TOTAL : []
result: []