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

与显示对象的格式相同。


当前回答

假设对象obj={0:'John',1:'Foo',2:'Bar'}

打印对象的内容

for (var i in obj){
    console.log(obj[i], i);
}

控制台输出(Chrome DevTools):

John 0
Foo 1
Bar 2

希望这有帮助!

其他回答

我使用了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;
};

你可以使用我的功能。使用数组或字符串或对象调用此函数,以提醒内容。

作用

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);

我总是使用console.log(“对象将是:”,obj,obj1)。这样我就不需要用JSON来解决字符串问题。对象的所有财产都将很好地展开。

var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);

它在浏览器中不起作用,您可能只需要在您希望获得对象的有效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 }))