ForEach javascript

0

Good, I am trying to set the forEach method for the Array class in javascript, to use it in a function that adds each element to a string. The object is a NodeofList, but I can not do it:

    NodeofList<Element>.forEach=funcion(){};

The code that I have is the following:

    Array.forEach += function (callback) {

    for (var i = 0; i < this.length; i++)
    callback(this[i], i, this);
    };

And here is where I try to use it:

    function funcionxml() {



     var mixml;
     var stringaMostrar = " ";//(en realidad esta variable la tengo como global)

     if (mipeticion.readyState == 4 && mipeticion.status == 200) {

        mixml = mipeticion.responseXML;
        var arrayPersonas = mixml.getElementsByTagName("persona");
        arrayPersonas.forEach(function (element, index, lista) {
            stringaMostrar += element.getElementsByTagName("nombre")[0].firstChild.nodeValue + " " + element.getElementsByTagName("apellidos")[0].firstChild.nodeValue + "\n";
        });


        document.getElementById("xml").innerHTML = stringaMostrar;
     }
    }

The error I receive is: arrayPersonas.forEach is not a function.

    
asked by Alexmaister 13.01.2018 в 02:10
source

2 answers

1

Even though you can access their positions, it is NOT an array, but an HTMLCollection, such as when you do:

document.getElementsByTagName("P")

This returns an HTMLCollection, to which you can access its indexes, but NOT to the methods of the Array class, since it is NOT.

var elems = document.getElementsByTagName("P"),
    toArray = Array.from(elems);

Array.from(Elemento iterable) , CREATE an array from an iterable object, as is an HTMLCollection, and why do I know it is iterable? Why can you access your indexes and iterate over it with a for cycle.

    
answered by 13.01.2018 / 15:16
source
1
  

I leave you like adding a new method to an object through its   prototype You were very close to achieving it. Greetings.

//Seteo el nuevo metodo del objeto Array
Array.prototype.myNewForEach = function(callback) {
  for (var a = 0; a < this.length; a++) {
    callback(this[a], a, this)
  }
}

// Forma de utilizarlo
var a = ["a", "b"]
a.myNewForEach(function(currentValue, index, array) {
  console.log("Index:", index)
  console.log("Elemento:", currentValue)
  console.log("Array:", array)
})
    
answered by 13.01.2018 в 05:59