[英]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.例如,如果我在 Chrome 控制台中输入$("p")
,我会得到[<p>Text1</p>,<p>..</p>]
,这正是我想要的。 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]
).现在我想将结果字符串存储到一个变量中并稍后重用它,但我还找不到方法( $("p").toString()
获取[Object Object]
)。
Is there a way to get the result string of console.log
in code?有没有办法在代码中获取console.log
的结果字符串?
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 :)如果您需要,我可以添加它,但在某些时候,查看 WebKit 开发人员工具的源代码可能会更容易:)
You can't.你不能。 console.log
does some magic that a string cant do. console.log
做了一些字符串不能做的魔法。 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)
.但正如@minitech 所指出的,你可以接近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.尽管这不适用于 DOM 元素,因为它们通常具有循环引用。 So you'd have to write your own function to crawl a jQuery object and dump it to a string.因此,您必须编写自己的函数来抓取 jQuery 对象并将其转储为字符串。 There isn't anything built in to do it for you.没有任何内置的东西可以为你做这件事。
You could try util-inspect你可以试试util-inspect
This is an extraction of Node's
inspect
utility from theutil
module, with two fundamental advantages:这是从util
模块中提取的 Node 的inspect
实用程序,具有两个基本优点:
- Single, focused module单一、专注的模块
- Compatible with all browsers and environments.兼容所有浏览器和环境。
Although it is compatible with browsers, it uses CommonJS so needs to be bundled first.虽然兼容浏览器,但使用的是CommonJS,所以需要先绑定。 But there's a fork that you can load directly in a browser via UNPKG .但是有一个分支,您可以通过UNPKG直接在浏览器中加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.