简体   繁体   中英

How to get result string of console.log in javascript code?

For example, if I enter $("p") in the chrome console, I get [<p>Text1</p>,<p>..</p>] , which is just what I want. Now I want to store the result string to a variable and reuse it later, but i couldn't find a way yet ( $("p").toString() gets [Object Object] ).

Is there a way to get the result string of console.log in code?

Well, here's something-ish:

function repr(obj) {
    if(obj == null || typeof obj === 'string' || typeof obj === 'number') return String(obj);
    if(obj.length) return '[' + Array.prototype.map.call(obj, repr).join(', ') + ']';
    if(obj instanceof HTMLElement) return '<' + obj.nodeName.toLowerCase() + '>';
    if(obj instanceof Text) return '"' + obj.nodeValue + '"';
    if(obj.toString) return obj.toString();

    return String(obj);
}

It isn't interactive or comprehensive. If you need that, I can add it, but at a certain point it might just be easier to look at the WebKit developer tools' source :)

You can't. console.log does some magic that a string cant do. It doesn't just render the object as a string. It also make the object structure interactive and clickable. It's rendering multiple interactive elements. The dev panel is taking a reference to an object and rendering it outside of where you code can reach.

But as @minitech notes, you can get close with JSON.stringify(myObject) .

var myObject = { a: 1, b: 2 };
myObject.toString();      // [object Object]
JSON.stringify(myObject); // {"a":1,"b":2}

Though this won't work with DOM elements, as they typically have circular references. So you'd have to write your own function to crawl a jQuery object and dump it to a string. There isn't anything built in to do it for you.

You could try util-inspect

This is an extraction of Node's inspect utility from the util module, with two fundamental advantages:

  • Single, focused module
  • Compatible with all browsers and environments.

Although it is compatible with browsers, it uses CommonJS so needs to be bundled first. But there's a fork that you can load directly in a browser via UNPKG .

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