问题描述
如果我有一个对象的构造函数,如:
if I have an object constructor like:
function cat(color, sex){
this.color = color;
this.sex = sex;
}
和我做一些猫:
var fluffball = new cat("blue","male");
var shiznitz = new cat("red","male");
var slothersburger = new cat("green","female");
是否有可能通过所有的猫环路我宣布?是这样的:
Is it possible to loop through all the cats I have declared? Something like:
var current_cat;
for(current_cat in document.cat){
alert(current_cat.color);
}
这不,虽然工作。难道人们通常存储在一个阵列中的所有猫对象?或使含个体猫的数组另一个对象:
That doesn't work though. Do people usually store all the cat objects in an array? Or make another object containing an array of the individual cats:
function all_cats(){
this.the_cats = new Array();
}
感谢您的任何提示!
Thanks for any tips!
推荐答案
这是不可能通过你所创建的所有对象的循环,除非你一直跟踪它们的地方(如在构造)。事情是这样的 -
It is not possible to loop through all the objects you have created unless you kept track of them somewhere (like in the constructor). Something like this-
var globalCatArray = [];
function cat(color, sex){
this.color = color;
this.sex = sex;
globalCatArray.push(this);
}
var fluffball = new cat("blue","male");
var shiznitz = new cat("red","male");
var slothersburger = new cat("green","female");
//use globalCatArray to get all instances
当心虽然。只要对象是在数组中,他们留在内存中没有垃圾收集。所以,如果你创建了很多对象,你可能想从数组中删除他们,一旦你用它做。
Watch out though. As long as the objects are in the array, they stay in memory without garbage collected. So if you create a lot of objects, you may want to remove them from the array once you are done with it.
另外,不要使用的for..in
来迭代虽然循环。看到这个http://stackoverflow.com/questions/1234449/javascript-array-extension/1234482
Also, do not use for..in
to iterate though loops. See this http://stackoverflow.com/questions/1234449/javascript-array-extension/1234482
这篇关于通过JavaScript对象的所有实例循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!