简体   繁体   中英

How can I add items in arraylist from a function? (JavaScript)

I have this function and I want to add this items in my arraylist. I know data.push(...) is not correct, so what it's the correct way?

          function addinfo(data) {
                var id = document.getElementById("courseid").value;
                var nm = document.getElementById("name").value;
                var yr = document.getElementById("year").value;
                var syll = document.getElementById("syllabus").value;
                var sem = document.getElementById("semester").value;
                var teach = document.getElementById("teaching").value;

                data.push(id,nm,yr,syll,sem,teach);
          }

          var data = [
              {
                courseid: "1",
                name: "Artificial Intelligence",
                year: "2021",
                syllabus: "3",
                semester: "2",
                teaching: "Johan"
              }
          ]

I assume you want to push all these values as an object into the data array. You could achieve that by doing the following. By giving the variables the same name as the keys in the object you can leave that out.

var data = [
  {
    courseid: "1",
    name: "Artificial Intelligence",
    year: "2021",
    syllabus: "3",
    semester: "2",
    teaching: "Johan"
  }
]

function addinfo(data) {
  var courseid = document.getElementById("courseid").value;
  var name = document.getElementById("name").value;
  var year = document.getElementById("year").value;
  var syllabus = document.getElementById("syllabus").value;
  var semester = document.getElementById("semester").value;
  var teaching = document.getElementById("teaching").value;

  data.push({courseid,name,year,syllabus,semester,teaching});
}          

Try this:

function addinfo(data) {
  data.push({
    courseid: document.getElementById("courseid").value,
    name: document.getElementById("name").value,
    year: document.getElementById("year").value,
    syllabus: document.getElementById("syllabus").value,
    semester: document.getElementById("semester").value,
    teaching: document.getElementById("teaching").value
  });
}

Maybe you can use a function that adds according to element ids stored in an array. Errors are not handled.

const fields = ["courseid", "name", "year", "syllabus", "semester", "teaching"];

function addinfo(anyFieldList, data) {
  const dataItem = {};
  for (let aField of anyFieldList){
    dataItem[aField] = document.getElementById(aField).value;
  }
  data.push(dataItem);
}

let data = [
  {
    courseid: "1",
    name: "Artificial Intelligence",
    year: "2021",
    syllabus: "3",
    semester: "2",
    teaching: "Johan"
  }
]

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