最大调用堆栈大小超出错误...如何修复?

时间:2017-02-17 06:46:58

标签: javascript arrays json object local-storage

我尝试编写待办事项列表,从输入表单中获取值,将其存储到对象中,将对象推送到数组中,对数组进行字符串化,将其存储在本地存储中,从中检索本地存储,并将其发布在表格中。

我收到错误"超出最大调用堆栈大小"参考我创建对象的行...我不完全确定我是否正在将输入字段中的值保存到对象中...帮助?谢谢

var table = document.getElementById("tableBody");

toDoArray = [];


function buildTable(){
addToStorage();
var retrievedTaskObject = localStorage.getItem("task");
var parsedObject = JSON.parse(retrievedTaskObject);
var addTheTaskName = parsedObject.taskName;
var addTheTaskDate = parsedObject.taskDate;
  var tableHTML = "";
  for(i=0; i < toDoArray.length; i++){
    var row = table.insertRow(0);
    var cellName = row.insertCell(0);
    var cellDate = row.insertCell(1);
    var cellId = row.insertCell(2);
    var cellCheck = row.insertCell(3);
    cellName.innerHTML= parsedObject[i].name;
    cellDate.innerHTML= parsedObject[i].date;
    cellId.innerHTML = 1 + i;
    var checkStuff = "<input type='checkbox'>";
    tableHTML += checkStuff;

  }
  document.getElementById("tableBody").innerHTML = tableHTML;
}

function submitForm(name,date) {
  var taskObject = {
    name: name,
    date: date,
  };

var addTaskName = document.getElementById("taskName").value;
var addTaskDate = document.getElementById("dateTask").value;
var taskSomething = submitForm(addTaskName,addTaskDate);
  toDoArray.push(taskObject);
  buildTable();
};

function addToStorage(){
  var storedArray = JSON.stringify(toDoArray);
  localStorage.setItem("task",storedArray);}

1 个答案:

答案 0 :(得分:1)

您正在通过调用iself中的submitForm方法进行递归。由于没有中断条件来停止递归,因此会发生最大堆栈错误

function submitForm(name,date) {
  var taskObject = {
    name: name,
    date: date,
  };

var addTaskName = document.getElementById("taskName").value;
var addTaskDate = document.getElementById("dateTask").value;
var taskSomething = submitForm(addTaskName,addTaskDate);
  toDoArray.push(taskObject);
  buildTable();
};

它应该是这样的 -

function submitForm(name,date) {
    var addTaskName = document.getElementById("taskName").value;
    var addTaskDate = document.getElementById("dateTask").value;
    var taskSomething = getTaskObj(addTaskName,addTaskDate);
      toDoArray.push(taskSomething);
      buildTable();
};

function getTaskObj(taskName,taskData){
var taskObject = {
        name: taskName,
        date: taskData,
      };
 return taskObject;
}