如何用javascript将用ES6代码创建的对象推送到数组中



所以我们有一个汽车对象数组,比如时间和速度。我们希望使用es6代码创建一个新对象,然后将其推送到数组中。我的代码返回空

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);

使用Array.push(item(

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

OR使用排列运算符:。。。

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

请遵循以下代码,这可能会有所帮助:

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);

最新更新