开发者

Is it possible to functionally traverse objects in JavaScript?

I think JavaScript doesn't have anything like obj.first, but I was wondering if something like this can be achieved in any way:

var foobar = { aint: "foo", an: "bar", array: "foobar" };
var recursiveObjDump = function (obj, idx) {
    if (idx == obj.last.index) return obj[idx];
    else return obj[idx] + " " + r开发者_运维技巧ecursiveObjDump(obj, obj[idx].next.index);
};

alert( recursiveObjDump(foobar, foobar.first.index) );

Thanks.


Not really. Objects in Javascript are associative arrays - sets of key/value pairs. There is no specified order, just as in a mathematical set (compare to a sequence). Therefore, looking for something like object.first is meaningless.

On the other hand, you can absolutely impose your own structure on top of this. For instance, you could implement Lisp-style lists in Javascript, and recur over those. This is a pretty neat article on using functional programming techniques in Javascript.

In the end, Javascript is object-oriented, not functional, so you're just not going to find those functional primitives implemented natively.

Edit: If you still want to use functional programming techniques in Javascript, have a look at Functional Javascript.


You can use for in to loop through all the properties.

This is a basic one, you could add better detection to look for Arrays and such as well.

var foobar = { aint: "foo", an: "bar", array: "foobar" };

function recusiveDump(obj) {
    var output = '';
    for(var i in obj) {
        if(obj.hasOwnProperty(i)) {
            if(typeof obj[i] == 'object') {
                output += recusiveDump(obj[i]);
            } else {
                output += obj[i];
            }
        }
    }
    return output;
}

alert(recusiveDump(foobar));


If you just want to serialize an object, use JSON.stringify(). It is native in Javascript 5, and you can download a script from Crockford's site for lower javascript versions. (the same script can reparse the JSON object serialization safely back to a javascript object again)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜