我正在尝试添加和删除" events"中的元素。 我不知道该怎么做。请有人帮帮我。我也尝试过splice()。
var events =
[
{ name: "Meeting 1", date: "Aug 2 2017", hour: "18:15" },
{ name: "Meeting 2", date: "Aug 1 2017", hour: "09:21" },
{ name: "Team", date: "Aug 1 2017", hour: "18:30" },
{ name: "St Mary Day", date: "Aug 15 2017", hour: "00:00" },
{ name: "St Andrew Day", date: "Nov 30 2017", hour: "00:00" },
{ name: "ROU National Day", date: "Dec 01 2017", hour: "00:00" },
{ name: "1st Day of Christmas", date: "Dec 25 2017", hour: "00:00" },
{ name: "2nd Day of Christmas", date: "Dec 26 2017", hour: "00:00" },
{ name: "Company Holiday", date: "Dec 27 2017", hour: "00:00" },
{ name: "Company Holiday", date: "Dec 28 2017", hour: "00:00" },
{ name: "Company Holiday", date: "Dec 29 2017", hour: "00:00" }
];
function myFunction() {
console.log("myfunction");
var input = document.getElementById('mod').value;
console.log("input is" + input);
events.forEach(function (events) {
console.log("enum events");
console.log(events.name);
if (events.name == input) {
var length = events.length;
console.log("aici");
events.push({ "name": "Tony Montana", "date": "Aug 3 2017", "hour": "18:00" });
}
});
}
答案 0 :(得分:0)
var events =
[
{ name: "Meeting 1", date: "Aug 2 2017", hour: "18:15" },
{ name: "Meeting 2", date: "Aug 1 2017", hour: "09:21" },
{ name: "Team", date: "Aug 1 2017", hour: "18:30" },
{ name: "St Mary Day", date: "Aug 15 2017", hour: "00:00" },
{ name: "St Andrew Day", date: "Nov 30 2017", hour: "00:00" },
{ name: "ROU National Day", date: "Dec 01 2017", hour: "00:00" },
{ name: "1st Day of Christmas", date: "Dec 25 2017", hour: "00:00" },
{ name: "2nd Day of Christmas", date: "Dec 26 2017", hour: "00:00" },
{ name: "Company Holiday", date: "Dec 27 2017", hour: "00:00" },
{ name: "Company Holiday", date: "Dec 28 2017", hour: "00:00" },
{ name: "Company Holiday", date: "Dec 29 2017", hour: "00:00" }
];
events.forEach(function (event) {
if (event.name == "Meeting 2") {
// Removes the "Meeting 2" element
events = events.filter(evt => evt.name != "Meeting 2")
// Pushes the "Tony Montana" element
events.push({ "name": "Tony Montana", "date": "Aug 3 2017", "hour": "18:00" });
}
});
console.log("events array is now", events)
关于要删除的元素,您的代码不会尝试删除元素,因此我不知道删除内容的条件。但是你总是可以过滤你的数组,例如:
events = events.filter( event => event.name!=="Meeting 2" )
将使用name : "Meeting 2"
删除元素。