如何像我们一样以字符串格式显示 JavaScript 对象的内容 alert 一个变量?

我想要显示对象的格式相同。

有帮助吗?

解决方案

如果您想打印物体进行调试,使用代码:

var obj = {prop1: 'prop1Value', prop2: 'prop2Value', child: {childProp1: 'childProp1Value'}}
console.log(obj)

将显示:

注意:您必须的只有的日志对象。例如,这将无法工作:

console.log('My object : ' + obj)

其他提示

使用天然JSON.stringify方法。 可与嵌套对象和所有主要浏览器支持此方法。

str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()

链接到 Mozilla的API参考和其它实例。

obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)

使用自定义 JSON.stringify替代品如果您 遇到此Javascript错误

"Uncaught TypeError: Converting circular structure to JSON"
var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);

console.dir(object)

  

显示指定JavaScript对象的属性的交互式列表。这个清单让你使用三角形以检查子对象的内容。

请注意的是,console.dir()特征是非标准的。请参见 MDN的Web文档

尝试这样:

console.log(JSON.stringify(obj))

此将打印对象的字符串化版本。因此,而不是[object]为输出你会得到对象的内容。

好吧,Firefox(感谢@Bojangles 提供详细信息) Object.toSource() 将对象打印为 JSON 的方法和 function(){}.

我想这对于大多数调试目的来说已经足够了。

如果你想使用警报,打印您的对象,你可以这样做:

alert("myObject is " + myObject.toSource());

有应该打印每个属性和以字符串格式及其相应的值。

在的NodeJS可以通过使用 util.inspect(obj) 。请务必注明深度或者你只有对象的浅打印。

如果你想看到在表格格式数据可以使用

console.table(obj);

如果你点击表列表进行排序。

您也可以选择显示哪些列:

console.table(obj, ['firstName', 'lastName']);

您可以在这里找到有关console.table 更多信息

<强>功能:

var print = function(o){
    var str='';

    for(var p in o){
        if(typeof o[p] == 'string'){
            str+= p + ': ' + o[p]+'; </br>';
        }else{
            str+= p + ': { </br>' + print(o[p]) + '}';
        }
    }

    return str;
}

<强>用法:

var myObject = {
    name: 'Wilson Page',
    contact: {
        email: 'wilson@hotmail.com',
        tel: '123456789'
    }  
}

$('body').append( print(myObject) );

示例:

http://jsfiddle.net/WilsonPage/6eqMn/

由于这是所述前最好和最简单的方式,我发现

var getPrintObject=function(object)
{
    return JSON.stringify(object);
}

使用这样的:

console.log('print object: ' + JSON.stringify(session));

要与打印完整的对象的 Node.js的颜色作为奖金:

console.dir(object, {depth: null, colors: true})

颜色当然可选的,“深度:空”。将打印完整的对象

的选项似乎并不在浏览器中被支持。

参考文献:

https://developer.mozilla.org/en-美国/文档/网络/ API /控制台/ DIR

https://nodejs.org/api/console.html#console_console_dir_obj_options

如果你想打印其全长的对象,可以使用

  

的console.log(要求( 'UTIL')检查(OBJ,{showHidden:假,深度:空}。)

如果你想通过将其转换为字符串,则打印对象

  

的console.log(JSON.stringify(OBJ));

(这已添加到我的图书馆中 GitHub)

在这里重新发明轮子!这些解决方案都不适合我的情况。所以,我很快修改了佩奇威尔的答案。这不适用于打印到屏幕(通过控制台、文本字段或其他方式)。然而,它用于数据传输。这个版本似乎返回了非常相似的结果 toSource(). 。我没试过 JSON.stringify, ,但我认为这是同一件事。该函数的结果是一个有效的 Javascript 对象声明。

我不会怀疑这样的东西是否已经在某个地方出现了,但制作它比花一些时间搜索过去的答案要短。因为当我开始搜索这个问题时,这个问题是我在谷歌上的热门搜索;我想把它放在这里可能会对其他人有所帮助。

无论如何,该函数的结果将是对象的字符串表示形式,即使您的对象具有嵌入的对象和数组,即使这些对象或数组具有进一步嵌入的对象和数组。(听说你喜欢喝酒?所以,我给你的车装了一个冷却器。然后,我用冷却器给你的冷却器拉皮条。因此,您的冷却器可以在您保持凉爽的同时喝酒。)

数组存储为 [] 代替 {} 因此没有键/值对,只有值。就像常规数组一样。因此,它们像数组一样被创建。

此外,所有字符串(包括键名)都被引用,除非这些字符串具有特殊字符(如空格或斜杠),否则这不是必需的。但是,我不想检测这一点只是为了删除一些否则仍然可以正常工作的引号。

然后可以将得到的字符串与 eval 或者只是通过字符串操作将其转储到 var 中。因此,从文本再次重新创建您的对象。

function ObjToSource(o){
    if (!o) return 'null';
    var k="",na=typeof(o.length)=="undefined"?1:0,str="";
    for(var p in o){
        if (na) k = "'"+p+ "':";
        if (typeof o[p] == "string") str += k + "'" + o[p]+"',";
        else if (typeof o[p] == "object") str += k + ObjToSource(o[p])+",";
        else str += k + o[p] + ",";
    }
    if (na) return "{"+str.slice(0,-1)+"}";
    else return "["+str.slice(0,-1)+"]";
}

如果我把一切搞砸了,请告诉我,在我的测试中工作正常。另外,我能想到的检测类型的唯一方法 array 是为了检查是否存在 length. 。因为 Javascript 确实将数组存储为对象,所以我实际上无法检查类型 array (没有这种类型!)。如果其他人知道更好的方法,我很想听听。因为,如果你的对象还有一个名为 length 那么这个函数就会错误地把它当作一个数组。

编辑:添加了对空值对象的检查。谢谢布洛克·亚当斯

编辑:下面是能够打印无限递归对象的固定函数。这与打印不一样 toSource 来自 FF 因为 toSource 将打印一次无限递归,其中,该函数将立即终止它。该函数的运行速度比上面的函数慢,因此我将其添加到此处,而不是编辑上面的函数,因为仅当您计划将链接回自身的对象传递到某处时才需要它。

const ObjToSource=(o)=> {
    if (!o) return null;
    let str="",na=0,k,p;
    if (typeof(o) == "object") {
        if (!ObjToSource.check) ObjToSource.check = new Array();
        for (k=ObjToSource.check.length;na<k;na++) if (ObjToSource.check[na]==o) return '{}';
        ObjToSource.check.push(o);
    }
    k="",na=typeof(o.length)=="undefined"?1:0;
    for(p in o){
        if (na) k = "'"+p+"':";
        if (typeof o[p] == "string") str += k+"'"+o[p]+"',";
        else if (typeof o[p] == "object") str += k+ObjToSource(o[p])+",";
        else str += k+o[p]+",";
    }
    if (typeof(o) == "object") ObjToSource.check.pop();
    if (na) return "{"+str.slice(0,-1)+"}";
    else return "["+str.slice(0,-1)+"]";
}

测试:

var test1 = new Object();
test1.foo = 1;
test1.bar = 2;

var testobject = new Object();
testobject.run = 1;
testobject.fast = null;
testobject.loop = testobject;
testobject.dup = test1;

console.log(ObjToSource(testobject));
console.log(testobject.toSource());

结果:

{'run':1,'fast':null,'loop':{},'dup':{'foo':1,'bar':2}}
({run:1, fast:null, loop:{run:1, fast:null, loop:{}, dup:{foo:1, bar:2}}, dup:{foo:1, bar:2}})

笔记:尝试打印 document.body 这是一个可怕的例子。其一,FF 在使用时仅打印一个空对象字符串 toSource. 。当使用上面的功能时,FF崩溃 SecurityError: The operation is insecure.. 。Chrome 会崩溃 Uncaught RangeError: Maximum call stack size exceeded. 。清楚地, document.body 并不意味着转换为字符串。因为它要么太大,要么违反安全策略来访问某些属性。除非,我在这里搞砸了一些事情,请告诉我!

我需要一种方法来递归打印对象,pagewil的答案提供了(谢谢!)。我更新它一点点地包括一个方法来打印到一定水平,并添加间隔,使得其适当的缩进基于所述电流电平,我们是在使其更具有可读性。

// Recursive print of object
var print = function( o, maxLevel, level ) {
    if ( typeof level == "undefined" ) {
        level = 0;
    }
    if ( typeof level == "undefined" ) {
        maxLevel = 0;
    }

    var str = '';
    // Remove this if you don't want the pre tag, but make sure to remove
    // the close pre tag on the bottom as well
    if ( level == 0 ) {
        str = '<pre>';
    }

    var levelStr = '';
    for ( var x = 0; x < level; x++ ) {
        levelStr += '    ';
    }

    if ( maxLevel != 0 && level >= maxLevel ) {
        str += levelStr + '...</br>';
        return str;
    }

    for ( var p in o ) {
        if ( typeof o[p] == 'string' ) {
            str += levelStr +
                p + ': ' + o[p] + ' </br>';
        } else {
            str += levelStr +
                p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}</br>';
        }
    }

    // Remove this if you don't want the pre tag, but make sure to remove
    // the open pre tag on the top as well
    if ( level == 0 ) {
        str += '</pre>';
    }
    return str;
};

用法:

var pagewilsObject = {
    name: 'Wilson Page',
    contact: {
        email: 'wilson@hotmail.com',
        tel: '123456789'
    }  
}

// Recursive of whole object
$('body').append( print(pagewilsObject) ); 

// Recursive of myObject up to 1 level, will only show name 
// and that there is a contact object
$('body').append( print(pagewilsObject, 1) ); 

简单地使用

JSON.stringify(obj)

实施例

var args_string = JSON.stringify(obj);
console.log(args_string);

或者

alert(args_string);

此外,在JavaScript函数注意被视为对象。

其实你可以指定新的属性这样

foo.moo = "stackoverflow";
console.log(foo.moo);

NB: 在这些例子中,定义了yourObj要检查的对象。

首先我最不喜欢显示对象的再利用最方式:

:此是示出对象的内容的事实上的方式

console.log(yourObj)

会产生类似: “在这里输入的图像描述”

我认为最好的办法是通过对象看起来键,然后通过对象中的值,如果你真的想看到的物体会怎样...

console.log(Object.keys(yourObj));
console.log(Object.values(yourObj));

它将输出是这样的: “在这里输入的图像描述” (上图:存储在所述对象中的键/值)

还有这个新的选项,如果你正在使用的ECMAScript 2016或更新:

Object.keys(yourObj).forEach(e => console.log(`key=${e}  value=${yourObj[e]}`));

这将产生整齐的输出: “在这里输入的图像描述” 在前面的回答中提到的解决方案:console.log(yourObj)显示太多的参数和是不是最用户友好的方式来显示你想要的数据。这就是为什么我推荐记录键,然后分别值。

下一步:

console.table(yourObj)

有人在较早的评论暗示这一个,但它从来没有为我工作。如果它不工作的人在不同的浏览器或东西,那么荣誉别的!生病还是把代码在这里供参考! 将输出这样的事情在控制台: “在这里输入的图像描述”

下面是一个办法做到这一点:

console.log("%o", obj);

最简单的方法:

console.log(obj);

或者与消息:

console.log("object is: %O", obj);

在通过第一对象可以包含一个或多个格式说明。格式说明由后跟一个字母,表示应用的格式百分号(%)的

更多格式说明

我总是用console.log("object will be: ", obj, obj1)。 这样我不需要做变通方法与JSON字符串化。 对象的所有属性将被很好地扩展。

控制台内显示物体的另一种方法是用JSON.stringify。检出以下示例:

var gandalf = {
  "real name": "Gandalf",
  "age (est)": 11000,
  "race": "Maia",
  "haveRetirementPlan": true,
  "aliases": [
    "Greyhame",
    "Stormcrow",
    "Mithrandir",
    "Gandalf the Grey",
    "Gandalf the White"
  ]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));
var list = function(object) {
   for(var key in object) {
     console.log(key);
   }
}

其中object是您的对象

也可以在Chrome浏览器开发工具的使用,“控制台”选项卡:

console.log(object);

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

打印对象的内容

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

控制台输出(铬DevTools):

John 0
Foo 1
Bar 2

希望帮助!

<强> Javascript函数

<script type="text/javascript">
    function print_r(theObj){ 
       if(theObj.constructor == Array || theObj.constructor == Object){ 
          document.write("<ul>") 
          for(var p in theObj){ 
             if(theObj[p].constructor == Array || theObj[p].constructor == Object){ 
                document.write("<li>["+p+"] => "+typeof(theObj)+"</li>"); 
                document.write("<ul>") 
                print_r(theObj[p]); 
                document.write("</ul>") 
             } else { 
                document.write("<li>["+p+"] => "+theObj[p]+"</li>"); 
             } 
          } 
          document.write("</ul>") 
       } 
    } 
</script>

<强>打印对象

<script type="text/javascript">
print_r(JAVACRIPT_ARRAY_OR_OBJECT);
</script> 

的print_r在Javascript

一个小助手功能,我总是在我的项目通过控制台使用简单,快速调试。  从Laravel采取启示。

/**
 * @param variable mixed  The var to log to the console
 * @param varName string  Optional, will appear as a label before the var
 */
function dd(variable, varName) {
    var varNameOutput;

    varName = varName || '';
    varNameOutput = varName ? varName + ':' : '';

    console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
}

<强>用法

dd(123.55);输出:结果 “在这里输入的图像描述”

var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj'); 

“在这里输入的图像描述”

我更喜欢使用console.table为获得清晰的目标文件格式,所以想象一下你有这样的对象:

const obj = {name: 'Alireza', family: 'Dezfoolian', gender: 'male', netWorth: "$0"};

你会看到一个整洁易读的表像这样如下: “console.table”

我用pagewil的打印方法,和它的工作非常漂亮。

这是我的稍延长版本(草率)缩进和不同支柱/ 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;
};

的pagewils代码的另一种修改......他不打印出来不是字符串任何东西,离开数和布尔领域空白,我固定在第二的typeof一样由megaboss创建函数内部的错字。

var print = function( o, maxLevel, level )
{
    if ( typeof level == "undefined" )
    {
        level = 0;
    }
    if ( typeof maxlevel == "undefined" )
    {
        maxLevel = 0;
    }

    var str = '';
    // Remove this if you don't want the pre tag, but make sure to remove
    // the close pre tag on the bottom as well
    if ( level == 0 )
    {
        str = '<pre>';   // can also be <pre>
    }

    var levelStr = '<br>';
    for ( var x = 0; x < level; x++ )
    {
        levelStr += '    ';   // all those spaces only work with <pre>
    }

    if ( maxLevel != 0 && level >= maxLevel )
    {
        str += levelStr + '...<br>';
        return str;
    }

    for ( var p in o )
    {
        switch(typeof o[p])
        {
          case 'string':
          case 'number':    // .tostring() gets automatically applied
          case 'boolean':   // ditto
            str += levelStr + p + ': ' + o[p] + ' <br>';
            break;

          case 'object':    // this is where we become recursive
          default:
            str += levelStr + p + ': [ <br>' + print( o[p], maxLevel, level + 1 ) + levelStr + ']</br>';
            break;
        }
    }

    // Remove this if you don't want the pre tag, but make sure to remove
    // the open pre tag on the top as well
    if ( level == 0 )
    {
        str += '</pre>';   // also can be </pre>
    }
    return str;
};

下面的功能。

function printObj(obj) {
console.log((function traverse(tab, obj) {
    let str = "";
    if(typeof obj !== 'object') {
        return obj + ',';
    }
    if(Array.isArray(obj)) {            
        return '[' + obj.map(o=>JSON.stringify(o)).join(',') + ']' + ',';
    }
    str = str + '{\n';
    for(var p in obj) {
        str = str + tab + ' ' + p + ' : ' + traverse(tab+' ', obj[p]) +'\n';
    }
    str = str.slice(0,-2) + str.slice(-1);                
    str = str + tab + '},';
    return str;
}('',obj).slice(0,-1)))};

它可以使用标签缩进与可读性显示对象。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top