将返回的对象推入对象数组

Push a returned object into an array of objects

我正在尝试将函数 setData(对象)的输出保存到数组 (state=[]),但不知道如何保存。这是代码:

const sbmt = document.getElementById("myForm");
const elName = document.getElementById("iname");
const elGender = document.getElementById("igender");
const elAge = document.getElementById("iage");
const elForm = document.getElementById("myForm");

const setData = (event) => {
    event.preventDefault();

    let nodeList = document.forms[0].elements;
    let flatNodeList = [...nodeList].map(x => x.value).filter(x => x !== "Submit");

    let objData = {
        userName: flatNodeList[0],
        userGender: flatNodeList[1],
        userAge: flatNodeList[2]
    };

    console.log(objData);

    return objData;
};

let state =[];

const resetForm = () => elForm.reset();

sbmt.addEventListener("submit", setData);
sbmt.addEventListener("submit", resetForm);

您基本上只需要将数据推送到您的 state 数组中。返回对象不会有任何影响。

let state =[];

const setData = (event) => {
    event.preventDefault();

    let nodeList = document.forms[0].elements;
    let flatNodeList = [...nodeList].map(x => x.value).filter(x => x !== "Submit");

    let objData = {
        userName: flatNodeList[0],
        userGender: flatNodeList[1],
        userAge: flatNodeList[2]
    };

    console.log(objData);

    state.push(objData);
};