如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?

与显示对象的格式相同。


当前回答

我使用了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 }))
var list = function(object) {
   for(var key in object) {
     console.log(key);
   }
}

其中object是您的对象

或者您可以在chrome开发工具的“控制台”选项卡中使用此选项:

console.log(对象);

试试这个:

var object = this.window;
console.log(object,'this is window object');

输出:

console.log()在调试对象方面做得很好,但如果您希望将对象打印到页面内容中,这里是我提出的模仿PHP print_r()功能的最简单方法。很多其他答案都想重新发明轮子,但在JavaScript的JSON.stringify()和HTML的<pre>标记之间,你可以得到你想要的东西。

var obj={name:'名称',联系人:{email:'thename@gmail.com',电话:'123456789'};$('body').append('<pre>'+JSON.stringify(obj,null,4)+'</pre>');<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script>

您还可以使用ES6模板文本概念以字符串格式显示JavaScript对象的内容。

alert(`${JSON.stringify(obj)}`);

常量对象={“name”:“John Doe”,“habbits”:“没有”,};警报(`${JSON.stringify(obj)}`);