[英]JavaScript - Iterating through objects in instance of object 'class'
I'm trying to iterate through all objects inside the instance of an object using pure JavaScript. 我正在尝试使用纯JavaScript遍历对象实例内的所有对象。
I tried something like this: 我尝试过这样的事情:
function a(){
this.iterate = function(){
for (var obj in this){
console.log(obj);
}
}
}
var A = new a();
A.insertedValue = 20;
A.iterate();
When doing this, instead of logging for example "20" for insertedValue it simply logs the name of the variable like "insertedValue". 这样做时,只需记录变量的名称(例如“ insertedValue”),而不是为insertedValue记录例如“ 20”。
Is there either a better way of looping through all objects in an instance of a object or a way to get the values from the objects I'm looping through? 有没有更好的方法可以遍历对象实例中的所有对象,或者有一种方法可以从我正在遍历的对象中获取值?
Is there either a better way of looping trough all objects in an instance of a object or a way to get the values from the objects I'm looping trough? 有没有一种更好的循环遍历对象实例中所有对象的方法,或者有一种方法可以从我正在循环遍历的对象中获取值?
Because you are simply printing the key inside this
rather than its value using this[obj]
. 因为您只是在this
键中打印键,而不是使用this[obj]
打印键值。
Make it 做了
function a(){
this.iterate = function(){
for (var obj in this){
console.log(this[obj]); //observe that this line has changed
}
}
}
The way you're doing it is largely correct, it's just that for-in
loops through the names of the object's properties, not their values. 您执行此操作的方式在很大程度上是正确的,只是for-in
循环遍历对象属性的名称 ,而不是其值。 So to output the property's value, you use this[name]
: 因此,要输出属性的值,请使用this[name]
:
function a(){
this.iterate = function(){
for (var name in this){
console.log(name + "=" + this[name]);
}
};
}
Note that for-in
will loop through the enumerable properties of the object, including ones it inherits from its prototype. 请注意, for-in
将遍历对象的可枚举属性,包括它从其原型继承的属性。 If you just want own properties, and not inherited ones, you can either check whether the property is an "own" property through hasOwnProperty
: 如果您只想要自己的属性,而不想要继承的属性,则可以通过hasOwnProperty
来检查该属性是否为“拥有”属性:
function a(){
this.iterate = function(){
for (var name in this){
if (this.hasOwnProperty(name)) {
console.log(name + "=" + this[name]);
}
}
};
}
Or use the handy Object.keys
, which gives you an array of own enumerable properties: 或使用方便的Object.keys
,它为您提供一系列自己的可枚举属性:
function a(){
this.iterate = function(){
Object.keys(this).forEach(function(name) {
console.log(name + "=" + this[name]);
});
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.