Error adding new instances in a Javascript array

Asked

Viewed 122 times

1

I’m having the following problem I have an array that adds the instance of an auxiliary object to the instance of an Htmlelement, but only the last element is being added, tested in the Chrome browser, Chromium, Opera and Mozilla Firefox and in none of them presented a different result.

This is the code in Coffeescript adding the instance in the array:

array = []
if not isEmpty(results)
    for result in results
        element = new VanillaHTMLDOMElement(result)
        console.log(element.getAttribute('id')) ##imprime o id do elemento normalmente
        array.push(element)
for item in array
    console.log item.getAttribute('id') ##imprime nulo para todos os casos
return array

This is the Javascript code adding the instance in the array:

var array, element, item, result, _i, _j, _len, _len1;
array = [];
if (!isEmpty(results)) {
  for (_i = 0, _len = results.length; _i < _len; _i++) {
    result = results[_i];
    element = new VanillaHTMLDOMElement(result);
    console.log(element.getAttribute('id')); //imprime o id do elemento normalmente 
    array.push(element);
  }
}
for (_j = 0, _len1 = array.length; _j < _len1; _j++) {
  item = array[_j];
  console.log(item.getAttribute('id')); //imprime nulo para todos os casos
return array
}
return array;

I believe it’s due to some form of Asymchronism, but I would like to confirm and I would like to know if anyone knows any solution?

  • 1

    I don’t know much about Vanilla, but apparently there is nothing wrong. Tried to create standard objects with the DOM and put in the array to see the output?

  • You have the function code VanillaHTMLDOMElement?

  • 1
  • I found the solution, the problem was in fact in the class Vanillahtmldomelement. Apparently the private attributes of Coffeescript are at the same time static, this meant that when I gave a new Vanillahtmldomelement(result), all instances of the Vanillahtmldomelement class pointed to the last result. Thanks for your help.

1 answer

-1

Instead of:

array.push(element);

Try to use:

array = [].push.apply(array, element);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.