Does Array.forEach not work in javascript?

0

I tried to iterate an array like this:

import { Vec2 } from './Math.js';
import Physics from "./Physics.js";
export default class Entity{
  constructor(x, y, w, h) {
    this.pos = new Vec2(x, y);
    this.scale = new Vec2(w, h);
    this.vel = new Vec2;
    this.traits = [];
    this.traits['physics'] = new Physics;
  }
  addTraits(name, trait) {
    this.traits.push(trait);
  }
  updateTraits(deltaTime, level) {
    //this.traits["physics"].update(deltaTime, this, level);
    this.traits.forEach(trait => {
        trait.update(deltaTime, this, level);
    });
  }
}

And neither the forEach nor the function is executed.

    
asked by FernandoGameYt 13.08.2018 в 00:45
source

2 answers

1

Actually when doing this.traits['physics'] you are defining a new property of the class ( this.traits.physics ) and not adding data to Array . The class Array only allows you to use Array.forEach() in the data stored in it, ignoring the properties you add.

However, you can iterate through each of the properties (including the data of Array ) through Reflect.ownKeys() .

Keep in mind that Array has a predefined property called length that contains the number of elements in the array, you'll have to deal with its existence.

In this example you can check these statements.

this.traits = [ 1, 2 ];
console.log('Tipo y constructor:', typeof this.traits, this.traits.constructor);
/* Esto agrega una propiedad a la instancia, y no un elemento al Array */
this.traits['physics'] = new Date();
/* Accedemos al contenido como si fuera una propiedad más */
console.log('Valor de la propiedad "physics":', this.traits.physics);
/* Agregamos más elementos al objeto de tipo Array */
this.traits.push(3);
this.traits.push(10);
/* Array.join unirá los elementos del Array, sin saber nada acerca de sus propiedades */
console.log('Unión:', this.traits.join(','));
/* Array.forEach navegará por los valores del Array, no por sus propiedades */
this.traits.forEach(trait => {
  console.log(trait);
});
/* Forma de iterar por sus propiedades */
Reflect.ownKeys(this.traits).forEach(clave => {
  console.log('Propiedad "' + clave + '"', this.traits[clave]);
});
    
answered by 13.08.2018 / 10:46
source
0

try with $this=this

updateTraits(deltaTime, level) {
    let $this= this;
    $this.traits.forEach(trait => {
        trait.update(deltaTime, this, level);
    });
}}
    
answered by 13.08.2018 в 06:11