简体   繁体   中英

.push is not a function, using Javascript and localstorage

I checked out all the links relating to this topic that I could and I found out that the reason why this is probably occurring is because my variable is not an array. I'm not too sure how to fix this. This is my code:

        function addStudent() {
            var newStudentInfo = {
                'studentNumber': document.getElementById("addStudentStudentNumber").value,
                'name': document.getElementById("addStudentName").value
            }

            var oldStudentInfo = [];
            oldStudentInfo = JSON.parse(localStorage.getItem("students")) || [];
            oldStudentInfo.push(newStudentInfo); 
            localStorage.setItem("students", JSON.stringify(oldStudentInfo));
        }

When looking at errors in google chrome, it tells me

Paused on exception: 'TypeError: oldStudentInfo.push is not a function'.

Where did I mess up? All help will be appreciated. Thanks!

clearly that's not an array you cannot invoke the push() method over an Object like that 'cause it does not have such a method. consider to push that object inside the original oldStudentInfo array like this:

function addStudent() {
  var newStudentInfo = {
      'studentNumber': document.getElementById("addStudentStudentNumber").value,
      'name': document.getElementById("addStudentName").value
  }

  var oldStudentInfo = JSON.parse(localStorage.getItem("students"));
  // now let's check if the stored value is an array
  if(!(oldStudentInfo instanceof Array))
    oldStudentInfo = [oldStudentInfo]; // if not, create one
  oldStudentInfo.push(newStudentInfo); // push a new student inside of it
  localStorage.setItem("students", JSON.stringify(oldStudentInfo));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM