2016-04-22 15 views
0

我的變量'todoList'顯示爲未定義。我對JavaScript和編程一般都很陌生。任何幫助將不勝感激!javascript:undefined變量

var todoList = { 
 
    todos:[], 
 
    displayTodos: function() { 
 
    if (this.todos.length === 0) { 
 
     console.log ('Your todos list is empty!'); 
 
    } else { 
 
     console.log('My Todos:'); 
 
     for (var i = 0; i < this.todos.length; i++) { 
 
     if (this.todos[i].completed === true) { 
 
      console.log ('(x)', this.todos[i].todoText); 
 
     } else { 
 
      console.log('()', this.todos[i].todoText); 
 
     } 
 
     } 
 
    } 
 
    }, 
 
    addTodo: function(todoText) { 
 
    this.todos.push({ 
 
     todoText: todoText, 
 
     completed: false 
 
    }); 
 
    this.displayTodos(); 
 
    }, 
 
    changeTodo: function(position, todoText) { 
 
    this.todos[position].todoText = todoText; 
 
    this.displayTodos(); 
 
    }, 
 
    deleteTodo: function(position) { 
 
    this.todos.splice(position, 1); 
 
    this.displayTodos(); 
 
    }, 
 
    toggleCompleted: function(position) { 
 
    var todo = this.todos[position]; 
 
    todo.completed = !todo.completed; 
 
    this.displayTodos(); 
 
    }, 
 
    toggleAll: function() { 
 
    var totalTodos = this.todos.length; 
 
    var completedTodos = 0; 
 
    for (var i = 0; i < totalTodos; i++) { 
 
     if(this.todos[i].completed === true) { 
 
     completedTodos++; 
 
     } 
 
    } 
 
    if (completedTodos === totalTodos) { 
 
     for(var i =0; i < totalTodos; i++) { 
 
     this.todos[i].completed === false; 
 
     } 
 
    } 
 
    this.displayTodos; 
 
    } 
 
};

+0

您的聲明和分配'todoList'的代碼看起來不錯。你需要提供更多關於你的代碼中變量是「未定義」的細節。 – smaili

+0

嘗試在你的if(this.todos [i] .completed === true)上添加'&&!this.todos [i] .todoText'' –

+0

也許你試圖從更高範圍訪問todoList對象,所以todoList不可見,因此未定義。 –

回答

0

的JavaScript總是返回東西。如果我將代碼複製/粘貼到Chrome控制檯並運行它,它會告訴我運行該代碼的返回結果是undefined。沒關係,因爲你只是設置了對象而無意使用返回值。

enter image description here

在此之後,已創建對象並鍵入它到Chrome的控制檯告訴我們,變量todoList是一個對象。

enter image description here

+0

謝謝!這真的很有幫助! – justinsunghokim

+0

很高興這是有益的,@justinsunghokim。如果你對我的回答滿意,你能接受嗎? –