如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?
与显示对象的格式相同。
当前回答
简单使用
JSON.stringify(obj)
实例
var args_string = JSON.stringify(obj);
console.log(args_string);
Or
alert(args_string);
此外,注意javascript函数被视为对象。
作为补充说明:
实际上,您可以像这样分配新属性并访问它console.log或在警报中显示它
foo.moo = "stackoverflow";
console.log(foo.moo);
alert(foo.moo);
其他回答
好吧,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和function(){}。
我想,对于大多数调试目的来说,这已经足够了。
看起来很简单。。。in无法解决这个问题,特别是当我们想要处理自定义、主机、本机或CSCOM对象之外的问题时。此外,我们正在讨论调试,谁知道我们何时何地需要它!
我的小型库可以处理以下对象:
obj2
|__ foo = 'bar'
|__ loop2 = obj2
| :
|__ another = obj1
|__ a1 = 1
|__ b1 = 'baz'
|__ loop1 = obj1
| :
|__ c1 = true
|__ d1 = ''
|__ e1 = [1,2,3]
并呈现出丰富多彩的标识,如:
0,foo,'bar'0,loop2,'包含对索引0'0处的对象的循环引用,另一个,'object'1,a1,11,b1,'baz'1,loop1,'包含索引2'1,c1,'true'1,d1,''1,e1,[1,2]处的对象循环引用
但请看这里:
https://github.com/centurianii/jsdebughttp://jsfiddle.net/centurianii/92Cmk/36/
通过一些预防措施,甚至可以解析document.body!
你可以使用我的功能。使用数组或字符串或对象调用此函数,以提醒内容。
作用
function print_r(printthis, returnoutput) {
var output = '';
if($.isArray(printthis) || typeof(printthis) == 'object') {
for(var i in printthis) {
output += i + ' : ' + print_r(printthis[i], true) + '\n';
}
}else {
output += printthis;
}
if(returnoutput && returnoutput == true) {
return output;
}else {
alert(output);
}
}
用法
var data = [1, 2, 3, 4];
print_r(data);
我使用了pagewil的打印方法,效果非常好。
这是我的略微扩展版本,带有(草率的)缩进和不同的prop/ob分隔符:
var print = function(obj, delp, delo, ind){
delp = delp!=null ? delp : "\t"; // property delimeter
delo = delo!=null ? delo : "\n"; // object delimeter
ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
var str='';
for(var prop in obj){
if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
}else{
str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
}
}
return str;
};
它在浏览器中不起作用,您可能只需要在您希望获得对象的有效JS表示而不是JSON的情况下使用它。它只运行节点内联求值
var execSync = require('child_process').execSync
const objectToSource = (obj) =>
execSync('node -e \'console.log(JSON.parse(`' + JSON.stringify(obj) + '`))\'', { encoding: 'utf8' })
console.log(objectToSource({ a: 1 }))