我有这段代码
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();
}
答案 0 :(得分: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();
}
<强> Fiddle 强>
为了更安全的一面:
for (var prop in obj) {
if (obj.hasOwnProperty([prop])) {
obj[prop].describeMyself();
}
}
答案 1 :(得分: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();
}
答案 2 :(得分:1)
var arr = [ rabbit1, rabbit2, rabbit3 ];
for (var i = 0; i < arr.length; ++i)
{
arr[i].describeMyself();
}