简体   繁体   English

Array.push 新对象,最后一个对象被推送

[英]Array.push new objects, last object pushed

I am trying to loop through an array of objects, which depending on their type property, will create a different class and append it to an array.我试图遍历一个对象数组,这些对象取决于它们的类型属性,将创建一个不同的类并将其附加到一个数组中。 The problem is that the output is always just a list of duplicates of the last class created.问题是输出始终只是创建的最后一个类的重复列表。

// 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)

After troubleshooting I've found that the problem isn't e , as each instance is different, however once it is pushed / added to the array, the problem occurs.故障排除后,我发现问题不是e ,因为每个实例都不同,但是一旦将其推送/添加到数组中,就会出现问题。 The problem only occurs when instances of Paragraph() are created.只有在创建Paragraph()实例时才会出现此问题。 As other items in the array, like text, will remain the same while still duplicating the last class.由于数组中的其他项目(如文本)将保持不变,同时仍然复制最后一个类。

Please can someone explain what I'm missing here?请有人解释我在这里缺少什么吗?

EDIT - Class for 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)
  }
}

The quill interacts with my html clone as intended.羽毛笔按预期与我的 html 克隆交互。 I hope this will help.我希望这将有所帮助。

The keyword is this in JavaScript. JavaScript 中的关键字是this Not self (that's a Python thing.) Since self is not a keyword in JavaScript, some people use it by convention as a normal variable name by manually assigning var self = this;不是self (这是 Python 的东西。)由于self不是JavaScript 中的关键字,因此有些人按照惯例通过手动分配var self = this;将其用作普通变量名var self = this; somewhere.某处。 But really, I think you just want to say this and use it the normal way .不过说真的,我觉得你只是想说this并使用它的正常方式

Replace self with this in your code and you should be good to go.在你的代码中用this替换self ,你应该很高兴。

Allow me to demonstrate a counterexample to your claim.请允许我为您的主张举一个反例。 You code seems to work correctly and the problem is elsewhere, most likely your Paragraph class.您的代码似乎工作正常,问题出在其他地方,很可能是您的Paragraph类。

By just changing the supporting framework (consisting of self and its content , page_data etc.) and the Paragraph class) I can demonstrate that your code (which I have used verbatim) works correctly, in that each element of self._elements is indeed different (most notably has a different id ).只需更改支持框架(由self及其contentpage_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)

Try just using a new variable declared inside the scope of the loop尝试只使用在循环范围内声明的新变量

// 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)

From your problem description, it sounds as if there is a single "reference" variable of 'e' and you are just creating an array of that reference over and over again, and whatever the loop last iterated over is what all those references point to从您的问题描述来看,听起来好像有一个“e”的“引用”变量,而您只是一遍又一遍地创建该引用的数组,无论最后一次迭代的循环是什么,所有这些引用都指向

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM