forEach no es un error de función con JavaScript array


Estoy tratando de hacer un bucle simple:

const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
  console.log(child)
})

Pero obtengo el siguiente error:

VM384:53 Uncaught TypeError: parent.niño.forEach no es una función

Aunque parent.children logs:

introduzca la descripción de la imagen aquí

¿Cuál podría ser el problema?

Nota: Aquí hay un JSFiddle.

Author: Yass, 2016-03-13

10 answers

El parent.children es un objeto similar a una matriz. Utilice la siguiente solución:

const parent = this.el.parentElement;
console.log(parent.children);
Array.prototype.forEach.call(parent.children, child => {
  console.log(child)
});

El parent.children es NodeList tipo, que es una Matriz como objeto porque:

  • Contiene la propiedad length, que indica el número de nodos
  • Cada nodo es un valor de propiedad con nombre numérico, a partir de 0: {0: NodeObject, 1: NodeObject, length: 2, ...}

Ver más detalles en este artículo.

 44
Author: Dmitri Pavlutin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-13 12:29:52

parent.children no es una matriz. Es HTMLCollection y no tiene el método forEach. Puede convertirlo a la matriz primero. Por ejemplo en ES6:

Array.from(parent.children).forEach(function (child) {
    console.log(child)
});

O usando el operador spread:

[...parent.children].forEach(function (child) {
    console.log(child)
});
 39
Author: madox2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-13 12:06:54

parent.children devolverá una lista de nodos, técnicamente una colección de elementos html. Es una matriz como objeto, pero no una matriz, por lo que no puede llamar a funciones de matriz directamente sobre ella. En este contexto puede usar Array.from() para convertir eso en una matriz real,

Array.from(parent.children).forEach(child => {
  console.log(child)
})
 8
Author: Rajaprabhu Aravindasamy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-13 12:07:41

parent.children es un HTMLCollection que es un objeto similar a una matriz. Primero, tienes que convertirlo a un Array real para usar los métodos Array.prototype.

const parent = this.el.parentElement
console.log(parent.children)
[].slice.call(parent.children).forEach(child => {
  console.log(child)
})
 5
Author: Dmitriy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-13 12:07:14

Esto se debe a que parent.children es un NodeList , y no admite el método .forEach (ya que NodeList es una estructura similar a una matriz, pero no una matriz), así que intente llamarlo primero convirtiéndolo en matriz usando

var children = [].slice.call(parent.children);
children.forEach(yourFunc);
 5
Author: Ammar Hasan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-13 12:08:00

Una versión más ingenua, al menos tu seguro de que funciona en todos los dispositivos, sin conversión y ES6 :

const children = parent.children;
for (var i = 0; i < children.length; i++){
    console.log(children[i]);
}

Https://jsfiddle.net/swb12kqn/5 /

 3
Author: Jean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-18 15:52:50

No hay ninguna necesidad de forEach, puede iterar usando solo el from's segundo parámetro, así:

let nodeList = [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]
Array.from(nodeList, child => {
  console.log(child)
});
 2
Author: Armfoot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-25 18:41:30

Dado que está utilizando características de ES6 ( arrow functions ), también puede usar simplemente un for loop así:

for(let child of [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]) {
  console.log(child)
}
 2
Author: Armfoot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-10 13:18:11

Si usted está tratando de bucle sobre un NodeList como este:

const allParagraphs = document.querySelectorAll("p");

Te recomiendo encarecidamente que lo hagas de esta manera:

Array.prototype.forEach.call(allParagraphs , function(el) {
    // Write your code here
})

Personalmente, he intentado varias maneras, pero la mayoría de ellas no funcionaron, ya que quería hacer un bucle sobre un NodeList, pero este funciona como un encanto, darle una oportunidad!

El NodeList no es un Array, pero lo tratamos como un Array, usando Array. Por lo tanto, ¡necesita saber que no es compatible con navegadores más antiguos!

¿Necesita más información sobre NodeList? Por favor lea su documentación sobre MDN.

 2
Author: Elharony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-26 22:03:45

Esto siempre ha funcionado para mí

const someElement = document.querySelectorAll('.someElement');

  someElement.forEach((element) => {
    // Your code here
  });
 0
Author: Khing James Enejo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 12:41:22