javascript 返回数组中的所有对象

vdzxcuhz  于 2023-02-02  发布在  Java
关注(0)|答案(3)|浏览(206)

我刚接触JavaScript,正在编写一个创建汽车对象并将其存储在数组中的个人程序,我在返回所有数组元素时遇到了问题,因为只返回了第一个数组元素。

const carFactory = {
    _cars:[
        {
            make: 'default',
            model: 'default',
            year: 0,
        }
    ],

    get cars(){
        if(this._cars.length > 0 ){
            for(let i = 0; i < this._cars.length; i++){
                return `Car Make: ${this._cars[i].make} - Car Model: ${this._cars[i].model} Manufacture Year: ${this._cars[i].year}`;
                }
        }else{
            return `Please add car details`;
            }
    },

    addCar(carMake, carModel, carYear){
        this._cars.push({
            carMake,
            carModel,
            carYear
        })
    }
}

carFactory.addCar('Toyota', 'Corolla', 2003);

console.log(carFactory.cars);
67up9zun

67up9zun1#

代码的问题在于for循环中的return语句只返回_cars数组中的第一个car对象并终止循环。要返回所有car,可以将car对象连接成一个字符串,并在循环后返回该字符串:

const carFactory = {
    _cars:[
        {
            make: 'default',
            model: 'default',
            year: 0,
        }
    ],

    get cars(){
        if(this._cars.length > 0 ){
            let allCars = '';
            for(let i = 0; i < this._cars.length; i++){
                allCars += `Car Make: ${this._cars[i].make} - Car Model: ${this._cars[i].model} Manufacture Year: ${this._cars[i].year}\n`;
            }
            return allCars;
        }else{
            return `Please add car details`;
        }
    },

    addCar(carMake, carModel, carYear){
        this._cars.push({
            make: carMake,
            model: carModel,
            year: carYear
        })
    }
}

carFactory.addCar('Toyota', 'Corolla', 2003);

console.log(carFactory.cars);
    • 输出:**
Car Make: default - Car Model: default Manufacture Year: 0
Car Make: Toyota - Car Model: Corolla Manufacture Year: 2003
gfttwv5a

gfttwv5a2#

for中有一个return,它将在第一次迭代时退出循环:

for(let i = 0; i < this._cars.length; i++){
  return `Car Make: ${this._cars[i].make} - Car Model: ${this._cars[i].model} Manufacture Year: ${this._cars[i].year}`;
 }
4dc9hkyq

4dc9hkyq3#

如果你想返回一个数组,那么就返回一个数组。2 addCar方法需要有正确名字。

const carFactory = {
    _cars: [
        {
            make: 'default',
            model: 'default',
            year: 0,
        }
    ],

    get cars() {
        if (this._cars.length > 0) {
            let allCars = [];
            for (let i = 0; i < this._cars.length; i++) {
                let c = `Car Make: ${this._cars[i].make} - Car Model: ${this._cars[i].model} Manufacture Year: ${this._cars[i].year}`;
                allCars.push(c)
            }
            return allCars
        } else {
            return `Please add car details`;
        }
    },

    addCar(make, model, year) {
        this._cars.push({
            make,
            model,
            year
        })
    }
}

carFactory.addCar('Toyota', 'Corolla', 2003);
console.log(carFactory.cars);

相关问题