迭代对象属性

时间:2009-07-31 20:59:51

标签: javascript

有没有办法迭代对象属性和方法。我需要写一个像这样的实用函数:

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

所以运行这个功能:

iterate(String);

将打印:

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

任何想法?

4 个答案:

答案 0 :(得分:13)

应该这么简单:

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

注意:console.log函数假设您正在使用firebug。此时,以下内容:

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

iterate(obj);

将返回:

number p1
string p2
function m1

答案 1 :(得分:6)

请参阅this other question中的答案,但您无法阅读此类内置属性。

答案 2 :(得分:3)

这仅适用于现代浏览器(Chrome,Firefox 4 +,IE9 +),但在ECMAScript 5中,您可以使用Object.getOwnPropertyNames获取对象的所有属性。只需要一些额外的代码就可以从原型中获取继承的属性。

// Put all the properties of an object (including inherited properties) into
// an object so they can be iterated over
function getProperties(obj, properties) {
    properties = properties || {};

    // Get the prototype's properties
    var prototype = Object.getPrototypeOf(obj);
    if (prototype !== null) {
        getProperties(prototype, properties);
    }

    // Get obj's own properties
    var names = Object.getOwnPropertyNames(obj);
    for (var i = 0; i < names.length; i++) {
        var name = names[i];
        properties[name] = obj[name];
    }

    return properties;
}

function iterate(obj) {
    obj = Object(obj);

    var properties = getProperties(obj);

    for (var name in properties) {
        if (typeof properties[name] !== "function") {
            console.log("property: " + name);
        }
    }
    for (var name in properties) {
        if (typeof properties[name] === "function") {
            console.log("function: " + name);
        }
    }
}

答案 3 :(得分:0)

您可以使用for循环来迭代对象的属性。

这是一个简单的例子

var o ={'test':'test', 'blah':'blah'};

for(var p in o)
    alert(p);
相关问题