开发者

"too much recursion" in this recursive function written in JavaScript (obj2str)

What's wront with this piece of code:

function obj2string(obj) {
    var result = '';

    for(var i in obj) {
        if(typeof(obj[i]) === 'object') {
            result += obj2string(obj[i]);
        } else {
            result += i + " => " + obj[i] + "\n";
        }
    }

    return result;
}

It's supposed to recursively concentate the result stri开发者_StackOverflow社区ng with new properties, however there's at somepoint too much recursion.

I was passing an object like this: $(this); -> from jQuery.

$(this)

Being an instance of this jQuery selector: $('.debug'); witch has one class matched in the current document.


if(typeof(obj[i]) === 'object') { will execute if obj[i] is null. Are you aware of that? Try it with $.isPlainObject() (source)


var s = JSON.stringify(obj, null, 4);


You almost certainly have a circular reference (i.e. one of the properties of the input object (or one of those property's properties, and so on)) references another property in the structure that leads back to itself.

A moment's thought should reveal why this can't possibly work.


Calling JSON.stringify( jQueryObject ) in the Chrome console gives a "circular_structure" error.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜