javascript - How do I get multiple returns from a for...in loop inside of a method? -
i'm learning javascript , decided try out working methods, constructors , this
keyword. made method finding cars based on words match words inside of property values. if turns out word matches value, returns object. problem is, when multiple objects have same property values, first of them returned. how of objects same value return? can solved or solution advanced? tried ton of variations this
keyword nothing worked.
//the constructor function car(make, model, year, condition){ this.make = make; this.model = model; this.year = year; this.condition = condition; } //an object holds properties 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 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 search cars cars.findcar(prompt("enter car make, model, year or condition").tolowercase());
you store cars in array :
findcar = function(find){ var finds = []; for(var 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; };
to avoid repetition :
findcar = function(find){ var finds = []; for(var in cars){ //loop through properties for(var j in cars[i]){ if(cars[i][j] === find){ finds.push(cars[i]); //if found, pass next car break; } } } //return results. return finds; };
next step add regexp search.
Comments
Post a Comment