如何推送到实际对象的数组最后状态,清除它并像新对象一样单独编辑
How to push to array last state of actual object, clear it and edit separately like new object?
单击"创建"按钮时如何将对象的最后状态添加到数组并创建新的干净准备继续,如果单击"继续"按钮仅修改实际对象,现在修改了部分数组中的所有对象?
说明性材料:
.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
对象,该库返回一个新对象。
相关文章:
- 什么'是从对象列表中一次编辑一个对象的正确Angular/Firebase方法
- 如何过滤对象内部深度堆叠的数据(并在之后编辑删除它)
- 在对象中追加或编辑函数的最快方法是什么
- 通过AngularJS中的模态编辑对象-使用临时对象
- Ace代码编辑器:缓存模式对象
- 使用<对象>用于SVG和HTML中的内联css以编辑填充
- 如何使用并行/多线程Hamsters.js Javascript库编辑数组中的对象属性
- Angular Schema Form-自定义对象编辑器
- 使用Vue.JS编辑数组的对象
- 如何在 angularjs 中从 cookie 中删除和编辑对象
- 使用可编辑对象进行分组
- 编辑对象 jQuery 的属性
- 编辑 ng 重复对象
- 如何推送到实际对象的数组最后状态,清除它并像新对象一样单独编辑
- 如何在第一个内容可编辑对象中创建元素
- 使用 JQuery 编辑对象标记的内容
- 将内容可编辑字段序列化为 JSON 对象以保存到模型的最佳方法是什么?
- 使用Json对象编辑下拉列表
- 如何在浏览器中将JSON对象编辑为表单
- 对象编辑的javascript对象