[英]Array.push new objects, last object pushed
我试图遍历一个对象数组,这些对象取决于它们的类型属性,将创建一个不同的类并将其附加到一个数组中。 问题是输出始终只是创建的最后一个类的重复列表。
// Create Elements from Content
// The id's are created by UUIDV4 and are all different.
self._elements = new Array
let e;
self.content.page_data.forEach(cont => {
switch (cont.type) {
case 'paragraph':
e = new Paragraph()
console.log(e.element.id)
self._elements.push(e)
break;
case 'title':
console.log('title')
return
}
})
console.log(self._elements)
故障排除后,我发现问题不是e
,因为每个实例都不同,但是一旦将其推送/添加到数组中,就会出现问题。 只有在创建Paragraph()
实例时才会出现此问题。 由于数组中的其他项目(如文本)将保持不变,同时仍然复制最后一个类。
请有人解释我在这里缺少什么吗?
编辑 - 段落类
class Paragraph {
constructor(value = '') {
self._element = template_paragraph.cloneNode(true).content.children[0];
const quil = self._element.children[0].children[1].children[0];
self.quill = new Quill(quil, {
modules: {
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
[{ list: 'ordered' }, { list: 'bullet' }]
]
},
placeholder: 'Compose an epic...',
theme: 'snow' // or 'bubble'
})
self._element.id = uuidv4()
}
get element() {
return self._element
}
set_content(content) {
// Set quill value
if (!content) return
//self.quill.setContents(content)
}
}
羽毛笔按预期与我的 html 克隆交互。 我希望这将有所帮助。
请允许我为您的主张举一个反例。 您的代码似乎工作正常,问题出在其他地方,很可能是您的Paragraph
类。
只需更改支持框架(由self
及其content
、 page_data
等组成)和Paragraph
类,我就可以证明您的代码(我逐字逐句地使用)工作正常,因为self._elements
每个元素确实不同(最值得注意的是具有不同的id
)。
// [[[ MOCKED FRAMEWORK TO DEMONSTRATE THAT YOUR CODE WORKS let self = { content: { page_data: [ {type:'title'}, {type:'paragraph'}, {type:'paragraph'}, ] } }; let nextUnusedId = 101; let Paragraph = function () { this.element = { id: nextUnusedId++ } } // ]]] // Create Elements from Content // The id's are created by UUIDV4 and are all different. self._elements = new Array let e; self.content.page_data.forEach(cont => { switch (cont.type) { case 'paragraph': e = new Paragraph() console.log(e.element.id) self._elements.push(e) break; case 'title': console.log('title') return } }) console.log(self._elements)
尝试只使用在循环范围内声明的新变量
// Create Elements from Content
// The id's are created by UUIDV4 and are all different.
self._elements = new Array
self.content.page_data.forEach(cont => {
switch (cont.type) {
case 'paragraph':
var e = new Paragraph()
console.log(e.element.id)
self._elements.push(e)
break;
case 'title':
console.log('title')
return
}
})
console.log(self._elements)
从您的问题描述来看,听起来好像有一个“e”的“引用”变量,而您只是一遍又一遍地创建该引用的数组,无论最后一次迭代的循环是什么,所有这些引用都指向
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.