1

我有这个代码

function Rabbit(adjective) {
this.adjective = adjective;
this.describeMyself = function() {
    console.log("I am a " + this.adjective + " rabbit");
};
}

var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");

rabbit1.describeMyself();
rabbit2.describeMyself();
rabbit3.describeMyself();

是否可以遍历同一类型的所有对象?

下面的方法似乎不起作用:

for (var e in Rabbit) {
return e.describeMyself();
}
4

3 回答 3

2

您可以这样做:使用 for-in 您只能遍历对象的属性,但不能获取范围内定义的变量。您定义的是未绑定到任何对象的变量。

var obj = { //Define your rabbits here.
    rabbit1: new Rabbit("fluffy"),
    rabbit2: new Rabbit("happy"),
    rabbit3: new Rabbit("sleepy")
}

for (var prop in obj) { //Now iterate through them
    obj[prop].describeMyself();
}

小提琴

为了更安全的一面:

for (var prop in obj) {
    if (obj.hasOwnProperty([prop])) { 
        obj[prop].describeMyself();
    }
}
于 2013-09-20T21:06:57.997 回答
1
var arr = [ rabbit1, rabbit2, rabbit3 ];

for (var i = 0; i < arr.length; ++i)
{
    arr[i].describeMyself();
}
于 2013-09-20T21:08:04.387 回答
1

不,JavaScript 并没有真正保存你创建的所有对象的列表,你必须自己做。或者,更准确地说,不保留一个您可以排序的列表,presto-chango。尝试一个数组:

var objects = []; //Our array

for(var i = 0; i<5; i++){
    //Let's make 5 objects!

    objects.push(new Object()); //Add this object to the array
}

//Later on when needed:

for(var i = 0; i<objects.length; i++){
    objects[i].myFunction();
}
于 2013-09-20T21:06:11.740 回答