0

我正在学习 javascript,我决定尝试使用方法、构造函数和this关键字。我制作了一种方法来根据与属性值中的单词匹配的某些单词来查找汽车。如果结果是一个词匹配一个值,那么它返回那个对象。问题是,当多个对象具有相同的属性值时,只返回其中的第一个。如何让所有具有相同值的对象返回?可以简单解决还是解决方案真的很先进?我尝试了this关键字的大量变体,但没有任何效果。

//The constructor
function car(make, model, year, condition){
    this.make = make;
    this.model = model;
    this.year = year;
    this.condition = condition;
}

//An object that holds properties that are really just more objects
var cars = {
car1: new car("Toyota", "Corolla", 2013, "New"),
car2: new car("Hyundai", "Sonata", 2012, "Used"),
car3: new car("Honda", "Civic", 2011, "Used") 
};

//The method
findCar = function(find){
for(var i in cars){
    if(cars[i].make.toLowerCase() === find){
        return cars[i];
    }
    else if(cars[i].model.toLowerCase() === find){
        return cars[i];
    }
    else if(cars[i].year === parseInt(find,10)){
        return cars[i];
    }
    else if(cars[i].condition.toLowerCase() === find){
        return cars[i];
    } 
}
};


cars.findCar = findCar;

//This is where I search for cars
cars.findCar(prompt("Enter a car make, model, year or condition").toLowerCase());
4

2 回答 2

1

您可以将汽车存储在这样的数组中:

findCar = function(find){
 var finds = [];
 for(var i in cars){
    if(cars[i].make.toLowerCase() === find){
        finds.push(cars[i]);
    }   
    else if(cars[i].model.toLowerCase() === find){
        finds.push(cars[i]);
    }
    else if(cars[i].year === parseInt(find,10)){
        finds.push(cars[i]);
    }
    else if(cars[i].condition.toLowerCase() === find){
        finds.push(cars[i]);
    }        
 }
 return finds;
};

为避免重复:

findCar = function(find){
    var finds = [];
    for(var i in cars){

        //Loop through properties
        for(var j in cars[i]){

            if(cars[i][j] === find){
                finds.push(cars[i]);
                //If found, pass to the next car
                break;
            }
        }
     }
     //Return results.
     return finds;
};

下一步是在搜索中添加一些正则表达式。

于 2014-05-31T23:13:19.407 回答
0

return 关键字将只返回一个对象,该对象可以是一个数组。此外,在执行返回后,您的函数中不会执行任何代码,因此您必须等到循环的所有迭代都完成后才能返回任何内容。在不重构您的任何逻辑(还有其他几个问题)并仅回答您的问题的情况下,这是您上面示例的修改后的代码:

//The method
findCar = function(find){
    var results = [];

    for(var i in cars){
        if(cars[i].make.toLowerCase() === find){
            results.push(cars[i]);
        }   
        else if(cars[i].model.toLowerCase() === find){
            results.push(cars[i]);
        }
        else if(cars[i].year === parseInt(find,10)){
            results.push(cars[i]);
        }
        else if(cars[i].condition.toLowerCase() === find){
            results.push(cars[i]);
        }        
    }

    return results;
};
于 2014-05-31T23:18:22.780 回答