[英]Create javascript object dynamic in a foreach loop
I want to create objects in a foreach loop: 我想在foreach循环中创建对象:
I'm starting from this: 我从这个开始:
data.forEach(function (el) {
var dynamic_var = new Quill(el['editor']);
dynamic_var.on('text-change', logHtmlContent);})
But, dynamic_var is 'overwritten', and I want to remain unique. 但是,dynamic_var被“覆盖”了,我想保持唯一性。
I check some html elements, and for each one that I found I want to create a new Object, and execute the Object methods. 我检查了一些html元素,发现的每个元素都想创建一个新的Object,并执行Object方法。
In my case the variable get a new object per each iteration, is not a new variable. 在我的情况下,变量每次迭代都获得一个新对象,而不是一个新变量。
Is this what you were looking for? 这是您要找的东西吗?
var quillValueContainer = {};
// ...
data.forEach(function(el) {
quillValueContainer[el] = new Quill(el['editor']);
quillValueContainer[el].on('text-change', logHtmlContent);
});
This will only work if el
is a string, or number. 仅当el
是字符串或数字时,这才有效。 Seeing how you are using it like this: el['editor']
, makes me thing it's an Object
, in which case, you can instead use the indices of the elements. 看看您是如何使用它的: el['editor']
,这使我觉得它是一个Object
,在这种情况下,您可以使用元素的索引。
var quillValueContainer = {}; // [] should also work for indexes
// ...
data.forEach(function(el, index) {
quillValueContainer[index] = new Quill(el['editor']);
quillValueContainer[index].on('text-change', logHtmlContent);
});
Also, I don't know if this is something you need to do, but you can check if the Quill
Object has already been initialized and skipping a duplication if it has, by doing: 另外,我不知道这是否是您需要做的事情,但是您可以通过执行以下操作来检查Quill
对象是否已经初始化,并跳过重复对象:
data.filter(function(el, index){ return !quillValueContainer[index]; }).foreach(...
Or 要么
data.forEach(function(el, index) {
if(quillValueContainer[index]) return;
quillValueContainer[index] = new Quill(el['editor']);
quillValueContainer[index].on('text-change', logHtmlContent);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.