Looping through all instances of a javascript object

后端 未结 5 2015
清酒与你
清酒与你 2020-12-10 07:01

if I have an object constructor like:

function cat(color, sex){
     this.color = color;
     this.sex = sex;
}

and I make some cats:

5条回答
  •  -上瘾入骨i
    2020-12-10 07:58

    since i just had a similar problem, here's one easy solution if you use jquery:

    function Cat(color, sex){
         this.color = color;
         this.sex = sex;
    }
    
    var cats = [];
    function createCat(color, sex)
    {
        cats.push(new Cat(color, sex)));
    }
    
    createCat("white", "male");
    createCat("black", "female");
    
    //iterating cats by using jQuery's $.each
    $.each(cats, function(index, object){
            alert(object.color);
    });
    

提交回复
热议问题