Home > Mobile >  adding some clases to array and looping them through this array?
adding some clases to array and looping them through this array?

Time:10-25

i am trying to push a class to an empty array . then use for to loop through classes in this array but it is not working. is there another way to loop through classes?nothing return in the console , no errors shown

let a=[]
class push_array{
  constructor (first , second) {
    this.first=first;
    this.second=second
    function pushing(){
      a.push(this)
      pushing()
      console.log(a)
      
    }
    
  }
  
}
const result=new push_array('fdsfs','fdsfdsf')

CodePudding user response:

pushing is called from within pushing, so the logic that pushes the instance to the array is never executed.

let a = []
class push_array {
  constructor(first, second) {
    this.first = first;
    this.second = second;
    a.push(this);
  }
}

const result = new push_array('fdsfs', 'fdsfdsf');
console.log(a);

Its unclear what your goal is, but using variable outside of a class could make your code complex very fast. If you're storing the result, why not just push the object to the array after instantiating?

let a = []

class push_array {
  constructor(first, second) {
    this.first = first;
    this.second = second;
  }
}

const result = new push_array('fdsfs', 'fdsfdsf');
a.push(result);

console.log(a);

CodePudding user response:

Assuming you have another reason for creating the class, what do you want to happen when the class is instantiated? Will you always push two items to an array? Why are you creating the class besides pushing some items to an array? How is this different than using .push()?

1. Using .push()

Assuming you are only pushing items to an array, how is this different than Array.prototype.push()?

let a = [];    
a.push("fdsfs", "fdsfdsf");

2. Store array in the class and push items on instantiation

Going back to the first assumption that you need to create a class, you likely want to keep the array tied to that class instance, rather than an outside variable:

class MyArrayClass {
  constructor(array, first, second) {
    this.array = array;
    array.push(first, second);
  }
  // does your class do anything else?
}

const result = new MyArrayClass([], "fdsfs", "fdsfdsf");
console.log("my array: ", result.array);

// using the class' array..
setTimeout(() => {
  result.array.push("some item");
  console.log("after item pushed :", result.array);
}, 100);

  • Related