我试图遍历每次单击动态创建的html时创建的数组,并且正在使用forEach函数遍历它。我的问题是,数组的forEach函数中仅显示最后一个对象,而数组中的其他值均未显示。这是我要执行的功能-
// //handler to show text from eventData array
document.addEventListener('click', (e)=> {
let noEvents = document.getElementsByClassName('no-Events')[0];
let eventsDescContainer = document.querySelector('.events');
if(e.target.classList.contains('day')){
[...eventData['events']].forEach((event)=>{
if(event['day']===e.target.innerHTML && event['month']===headerMonths.innerHTML && event['year']===headerYears.innerHTML){
//the event['day'], event['month'], and event['year'] values are not looping through the array, they are only showing whatever the last object values I added to the eventData array
//show event Text
showEventText(event['description'], event['month'], event['year'], event['day']);
} else {
console.log(e.target.innerHTML + event['day']);
console.log(headerMonths.innerHTML + event['month'])
console.log(headerYears.innerHTML + event['year']);
console.log(eventData['events']);
clearEventText(headerYears.innerHTML);
noEvents.style.display='initial';
noEvents.innerHTML = `There are no events on ${headerMonths.innerHTML} ${e.target.innerHTML} ${headerYears.innerHTML}`;
//reverse flexDirection to original direction
eventsDescContainer.style.flexDirection = 'column';
}
});
}
});
//JSON event data
let eventData = {
"events": [
{
"description": 'es',
"year": '2018',
"month": 'Nov',
"day": '28'
}
]
};
它循环遍历eventData数组,但是如果我向eventData数组添加另一个对象,并且尝试在eventListener中循环遍历它,则eventListener将仅获取我刚刚添加到数组中的项目,这是最后一个数组中的对象,并且不会遍历数组的其余部分来获取较旧的对象。
event ['day'],event ['month']和event ['year']值不在数组中循环,它们仅显示我添加到eventData数组中的最后一个对象值>
为什么会这样,我该如何解决?
编辑:
这是我用来向eventData数组添加新对象的功能
//adds json to eventData
function newEventJson(description, month, year, day){
let event = {
"description": description,
"year": year,
"month": month,
"day": day
};
eventData.events.push(event);
}
当我使用console.log在eventListener中调试它时,eventData ['events']显示数组中的所有值,但是event ['day],event ['month']和event [' year']都与eventData数组中的最后一项保持相同的值。
这里是指向https://codepen.io/icewizard/pen/ZmJByP的代码笔的链接。