so here is my code below. I kind of expected the three functions to return the following in order, as that would make logical sense as the functions were invoked in this order:
- [{First, false}]
- [{First, false}, {Second, false}]
- [{Change, false}, {Second, false}]
But that's not what happened...what ends up happening is I get the exact same return for all the functions!? Results as follows:
- [{Change, false}, {Second, false}]
- [{Change, false}, {Second, false}]
- [{Change, false}, {Second, false}]
How is this possible? Can anyone please explain what is going on?
Here is the code:
var todolist = {
todos: [],
displayt: function(){
console.log(this.todos);
},
addTodo: function(todoText){
this.todos.push({
todoText: todoText,
completed: false
});
this.displayt();
},
changeTodo: function(pos, todoText) {
//this.todos[pos] = val;
this.todos[pos].todoText = todoText;
this.displayt();
}
}
todolist.addTodo('First');
todolist.addTodo('Second');
todolist.changeTodo(0, 'Change');
Here is my JSfiddle, and when I run it I open the console in Chrome to see the results.
THANKS!! THIS IS DRIVING ME INSANE
EDIT: OKAY! Looks like this is a chrome issue with console.log() and arrays/objects. If I modify the code (below) I can get the expected results, thanks u/jones1618
var todolist = {
todos: [],
displayt: function(){
for (var i = 0; i<this.todos.length; i++){
console.log(this.todos[i].todoText);
}
},
addTodo: function(todoText){
this.todos.push({
todoText: todoText,
completed: false
});
this.displayt();
},
changeTodo: function(pos, todoText) {
//this.todos[pos] = val;
this.todos[pos].todoText = todoText;
this.displayt();
}
}
todolist.addTodo('First');
todolist.addTodo('Second');
todolist.changeTodo(0, 'Change');