简体   繁体   中英

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.

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".

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] .

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. So to output the property's value, you use 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. If you just want own properties, and not inherited ones, you can either check whether the property is an "own" property through 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:

function a(){
    this.iterate = function(){
        Object.keys(this).forEach(function(name) {
            console.log(name + "=" + this[name]);
        });
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM