如何从方法中的for ... in循环中获得多个返回值?

时间:2014-05-31 22:48:06

标签: javascript methods return-value construct

我正在学习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());

2 个答案:

答案 0 :(得分: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;
};

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

答案 1 :(得分: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;
};