计算其他对象中的匹配对象

时间:2013-05-13 12:08:21

标签: javascript oop object

让我详细说明这个问题:

我想定义一个父对象,例如usedCars。然后在usedCars里面我想添加一些汽车。当然,我希望能够根据milage计算匹配的usedCars的数量。

这是我正在使用的,但因为我是新手,我不能前进!

    var usedCar = {
        //constructor for cars
        car: function(model, year, miles){ 
            this.model = model;
            this.year  = year;
            this.miles = miles;
        },
        //some objects
    }

所以如果我实例化一个新的usedCar我应该做以下吗?

    var shelby = new usedCar.car('Shelby', 1990, 7500); 
    // i have no idea is this working or not!

所以,如果一切正常,我想计算匹配的usedCar的数量

    usedCar.prototype.findIt = function(maxMilage){
        //should i use for in or something like that here?
        // i want to search through many available used cars and 
        // count based on maxMilage arg.
    }
有人能帮帮我吗?我知道我在JS和英语中都很蹩脚,哈哈。 如果我错了,请给我一些关于如何实施这种情况的建议。

谢谢大家。

2 个答案:

答案 0 :(得分:3)

var usedCar = {
    carList: [],
    findIt: function(maxMileage) {
        var result = [];
        for(var i=0;i<usedCar.carList.length;i++){
            if(usedCar.carList[i].miles < maxMileage) {
               result.push(usedCar.carList[i]);   
            }
        }
        return result;
    },
    //constructor for cars
    car: function(model, year, miles){ 
        this.model = model;
        this.year  = year;
        this.miles = miles;
        usedCar.carList.push(this);
    },
    //some objects
}
var shelby = new usedCar.car('Shelby', 1990, 7500);  
var searchResults = usedCar.findIt(10000);  
console.log(searchResults.length);   // Number of matching cars

答案 1 :(得分:0)

在记事本中写道,但这应该有用..

function maxMilage(number) {
int counter =  0;
for (var i=0;i<usedCar.carList.length;i++)
{ 
    if(usedCar[i].miles < number)
    { counter++; }
}
console.log(counter);
}