Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating an object properties

Tags:

javascript

is there a way to iterate an object properties and methods. i need to write a utility function like so:

function iterate(obj)
{
    //print all obj properties     
    //print all obj methods
}

so running this function:

iterate(String);

will print:

property: lenght
function: charAt
function: concat...

any ideas?

like image 822
Amir Avatar asked Nov 29 '22 06:11

Amir


1 Answers

Should be as simple as this:

function iterate(obj) {
    for (p in obj) {
        console.log(typeof(obj[p]), p);
    }
}

Note: The console.log function is assuming you are using firebug. At this point, the following:

obj = {
    p1: 1, 
    p2: "two",
    m1: function() {}
};

iterate(obj);

would return:

number p1
string p2
function m1
like image 129
sixthgear Avatar answered Dec 13 '22 09:12

sixthgear