如何推送到实际对象的数组最后状态,清除它并像新对象一样单独编辑

How to push to array last state of actual object, clear it and edit separately like new object?

本文关键字:对象 编辑 新对象 单独 一样 清除 何推送 数组 状态 最后      更新时间:2023-09-26

单击"创建"按钮时如何将对象的最后状态添加到数组并创建新的干净准备继续,如果单击"继续"按钮仅修改实际对象,现在修改了部分数组中的所有对象?

说明性材料:

.HTML:

<button onclick="create()">Create</button>
<button onclick="add()">Continue</button>

JavaScript:

var sections = [];
create = function() {
    sections.push(section);
    section.array = [];
    section.c = 0;
    section.add();
    $("body").append("<br>Add to array at moment last state of object and make new one<br>" + JSON.stringify(sections) + "<br >");
}
add = function() {
    section.add();
    $("body").append("<br>continue only this object<br>" + JSON.stringify(sections) + "<br >");
}
var section = {
    array: [],
    c: 0,
    add: function() {
        section.c++;
        section.array.push(section.c);
    }
}​
您需要

创建新的 section 对象,而不是重置一个section变量的属性(在 create 函数中(:

var sections = [],
section = makeSection();
function create() {
    sections.push(section); // add the current section
    section = makeSection(); // make a new one
    section.add();
    $("body").append("<br>Add to array at moment last state of object and make new one<br>" + JSON.stringify(sections) + "<br >");
}
function add() {
    section.add();
    $("body").append("<br>continue only this object<br>" + JSON.stringify(sections) + "<br >");
}
function makeSection() {
    return {
        array: [],
        c: 0,
        add: function() {
            section.c++;
            section.array.push(section.c);
        }
    }​;
}

然而,我会说这是构造函数的一个案例:

function Section() {
    this.array = [];
    this.c = 0;
    // maybe do this automatically on constructing:
    // this.add();
    // sections.push(this);
}
Section.prototype.add = function() {
    this.c++;
    this.array.push(section.c);
}

然后使用 new Section() 而不是 makeSection() .

试试这个:

sections.push(JSON.parse(JSON.stringify(section)));

这有点笨拙,但它会将对象的新副本推送到数组sections,而不是引用,从而有效地保存对象的状态。这段代码实际执行的是使用 JSON 库stringify然后parse对象,该库返回一个新对象。