简体   繁体   中英

“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 string 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.

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

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

You almost certainly have a circular reference (ie 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.

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