我正在学习javaScript并开发todoList应用程序。我已将所有内容放入一个名为todoList的对象中,然后首先有一个对象数组将任务存储在todoList中。每个对象都有两个属性,即(todo = text,status = boolean)。之后是一个showTasks
用于在todoList中显示任务的函数。showTasks
函数中有一个if语句,用于检查todoList是否为空。之后是for循环,用于显示阵列中的所有任务。另一个if语句位于for循环之后,以显示任务的状态。该addTask
函数用于在列表中添加新任务,该列表仅添加任务的文本,而不添加状态(默认情况下,状态为false)。在editTask
与deleteTask
函数是很容易解释的。最后一个称为toggleStatus的功能是切换任务的状态,它不起作用,我不知道为什么。
var todoList = {
// Storing tasks
tasks: [],
// Displaying tasks
showTasks: function() {
if (this.tasks.length === 0) {
console.log("There's no tasks in the list.");
} else {
console.log("My Tasks:");
for (var i = 0; i < this.tasks.length; i++) {
if (this.tasks.status === true) {
console.log("(X)", this.tasks[i].todo);
} else {
console.log("( )", this.tasks[i].todo);
}
}
}
},
// Adding a new task
addTask: function(task) {
this.tasks.push({
todo: task,
status: false
});
this.showTasks();
},
// Editing an existing task
editTask: function(count,task) {
this.tasks[count].todo = task;
this.showTasks();
},
// Deleting a task
deleteTask: function(count) {
this.tasks.splice(count,1);
this.showTasks();
},
// Changing status
toggleStatus: function(count) {
var task = this.tasks[count];
task.status = !task.status;
this.showTasks();
}
};
您if
的for
循环陈述中有错别字:D
这是很好的语法:
if (this.tasks[i].status) {
顺便说一句,我会这样写,原型更好,因为您的对象存储的功能不如声明的对象那么多,因此创建起来更快;)参见JS-为什么使用原型?
function TodoList() {
// Storing tasks
this.tasks = [];
}
TodoList.prototype = {
// Displaying tasks
showTasks: function() {
if (this.tasks.length === 0) {
console.log("There's no tasks in the list.");
} else {
console.log("My Tasks:");
for (var i = 0; i < this.tasks.length; i++) {
if (this.tasks[i].status) {
console.log("(X)", this.tasks[i].todo);
} else {
console.log("( )", this.tasks[i].todo);
}
}
}
},
// Adding a new task
addTask: function(task) {
this.tasks.push({
todo: task,
status: false
});
this.showTasks();
},
// Editing an existing task
editTask: function(count, task) {
this.tasks[count].todo = task;
this.showTasks();
},
// Deleting a task
deleteTask: function(count) {
this.tasks.splice(count, 1);
this.showTasks();
},
// Changing status
toggleStatus: function(count) {
var taskStatus = !this.tasks[count].status;
this.tasks[count].status = taskStatus;
this.showTasks();
}
};
var t = new TodoList();
t.addTask("yowwww");
t.addTask("miaou");
t.editTask(1, "miawwwwwou");
t.toggleStatus(0)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句