循环遍历 javascript 对象的所有实例 [英] Looping through all instances of a javascript object

查看:32
本文介绍了循环遍历 javascript 对象的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个对象构造函数,例如:

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);
}

虽然那行不通.人们通常将所有 cat 对象存储在一个数组中吗?或者创建另一个包含单个猫的数组的对象:

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();
}

感谢您的建议!

推荐答案

除非您在某处(例如在构造函数中)跟踪它们,否则不可能遍历您创建的所有对象.像这样-

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 来遍历循环.请参阅此 Javascript 数组扩展

Also, do not use for..in to iterate though loops. See this Javascript Array extension

这篇关于循环遍历 javascript 对象的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆