-3

So we have an array of car objects such as time and speed. We want to create a new object using es6 code and then push it into the array. My code returns null

const carPassing = (cars, speed) => {

  class newVehicle {
    constructor(time, speed) {
      this.time = Date.now();
      this.speed = speed;
    }
  }

  console.log(person.time);
  console.log(person.speed);
  cars.push();
  console.log(cars);

  return cars;
};
adiga
  • 34,372
  • 9
  • 61
  • 83
  • 1
    You never called `new newVehicle()` – Barmar Nov 16 '19 at 19:55
  • 2
    and you never pass anything to `push()` – Mark Nov 16 '19 at 19:55
  • And you never set `person`. – Barmar Nov 16 '19 at 19:56
  • 1
    Also, it's pretty unusual to have a class definition inside a function definition. I think it will work, but it's strange. – Barmar Nov 16 '19 at 19:57
  • You are pushing nothing into your array – Masood Nov 16 '19 at 19:58
  • What is the `time` parameter to the constructor for? You don't use it, you use `Date.now()` as the value in the object. – Barmar Nov 16 '19 at 19:58
  • 1
    A `class` is like a template for an object, not an object itself. You define the template once, then use the `new` keyword to create instances of the template every time you need one. – Heretic Monkey Nov 16 '19 at 20:00
  • It would help someone give you an idea of how to do this if you showed how you are calling the function, what `cars` looks like, and what you are expecting as a result. – Mark Nov 16 '19 at 20:00
  • 1
    Possible duplicate of [How to add an object to an array](https://stackoverflow.com/questions/6254050/how-to-add-an-object-to-an-array) – Heretic Monkey Nov 16 '19 at 20:02

3 Answers3

1

You have to create the object with new, then push it onto the array.

class newVehicle {
  constructor(speed) {
    this.time = Date.now();
    this.speed = speed;
  }
}

const carPassing = (cars, speed) => {
  const person = new newVehicle(speed);
  console.log(person.time, person.speed);
  cars.push(person);
  console.log(cars);
  return cars;
};

let allCars = [];
allCars = carPassing(allCars, 100);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Use Array.push(item)

var car = {time: Date.now(), speed: 60}; 
this.cars.push(car);

OR using spread operator:...

var car = [{time:  Date.now(), speed: 60}];
this.cars.push(...car);
junlan
  • 302
  • 1
  • 5
0

Please follow below code, this might be helpful:

enter code here
let carsList = [];
const carPassings = (carsList, speed) => {
class newVehicle {
    constructor(time, speed) {
        this.time = time;
        this.speed = speed;
    }
}
var person = new newVehicle(Date.now(), speed);
console.log(person.time);
console.log(person.speed);
carsList.push({
    person.time,
    person.speed
});
console.log(carsList);
};
carPassings(carsList, 140);
Sarvesh Mahajan
  • 914
  • 7
  • 16