Tengo una lista de objetos. Cada objeto tiene una propiedad que es una lista de elementos:
{ name : 'Club 01' , id : 1 , form : 45 , points : 0 , tactics : 'neutral' , played : 0 , gameset : 0 , playedWith : [ 8, 1, 2, 3 ] }Quiero revisar la lista y registrar en la consola todos los elementos existentes:
for (let a = 0; a<clubs.width; a++) { for (let b = 0; b<clubs[a].playedWith.width; b++) { console.log(clubs[a].playedWith[b]); } }cuando lo hago para un artículo, esto funciona. sin embargo, cuando lo hago con un bucle como el anterior, esto me lleva a
undefined¿Qué pasa con mi código? ¿Cómo registro en la consola todos los elementos dentro de la propiedad playWith?
Elikill58 tiene razón. Los arreglos tienen la propiedad de longitud , no la propiedad de ancho .
Entonces su código funcionaría bien de esta manera:
for (let a = 0; a < clubs.length; a++){ for (let b = 0; b < clubs[a].playedWith.length; b++){ console.log(clubs[a].playedWith[b]); } }Además, si desea iterar a través de todos los elementos de la matriz, solo por simplicidad, puede escribirlo así:
for (const club of clubs) { for (const width of club.playedWith) { console.log(width); } }let b = { nombre: 'Club 01', id: 1, formulario: 45, puntos: 0, tácticas: 'neutral', jugado: 0, juego: 0, jugado con: [8, 1, 2, 3],
move: function() { return ` ${ this.name }and ${this.id }and ${ this.form }and ${ this.points }and ${ this.tactics }and ${ this.played }and ${ this.gameset }and ${ this.playedWith }` }};
consola.log(b.mover()) para (var w en b) { consola.log( ${w}:${b.move()} ) }
Tienes que usar la length en lugar del width para ambos bucles.
Aquí hay un ejemplo :
var clubs = [ { name : 'Club 01' , id : 1 , form : 45 , points : 0 , tactics : 'neutral' , played : 0 , gameset : 0 , playedWith : [ 8, 1, 2, 3 ] } ]; for (let a = 0; a < clubs.length; a++) { for (let b = 0; b < clubs[a].playedWith.length; b++) { console.log(clubs[a].playedWith[b]); } }