javascript - 如何将使用 ES6 代码创建的对象推送到 javascript 中的数组中
问题描述
所以我们有一系列汽车对象,例如时间和速度。我们想使用 es6 代码创建一个新对象,然后将其推送到数组中。我的代码返回 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;
};
解决方案
您必须使用 创建对象new
,然后将其推送到数组中。
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);