How can I display a JavaScript object?

2018-12-31 03:25发布

How do I display the content of a JavaScript object in a string format like when we alert a variable?

The same formatted way I want to display an object.

30条回答
临风纵饮
2楼-- · 2018-12-31 03:47

Another way of displaying objects within the console is with JSON.stringify. Checkout the below example:

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));
查看更多
时光乱了年华
3楼-- · 2018-12-31 03:48

A little helper function I always use in my projects for simple, speedy debugging via the console. Inspiration taken from 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) + ')');
}

Usage

dd(123.55); outputs:
enter image description here

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

enter image description here

查看更多
余欢
4楼-- · 2018-12-31 03:48

Another modification of pagewils code... his doesn't print out anything other than strings and leaves the number and boolean fields blank and I fixed the typo on the second typeof just inside the function as created by 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;
};
查看更多
浪荡孟婆
5楼-- · 2018-12-31 03:48

A simple way to show the contents of the object is using console.log as shown below

console.log("Object contents are ", obj);

Please note that I am not using '+' to concatenate the object. If I use '+' than I will only get the string representation if object, something like [Object object].

查看更多
骚的不知所云
6楼-- · 2018-12-31 03:49

The simplest way:

console.log(obj);

Or with a message:

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

The first object you pass can contain one or more format specifiers. A format specifier is composed of the percent sign (%) followed by a letter that indicates the formatting to apply.

More format specifiers

查看更多
旧时光的记忆
7楼-- · 2018-12-31 03:50
var list = function(object) {
   for(var key in object) {
     console.log(key);
   }
}

where object is your object

or you can use this in chrome dev tools, "console" tab:

console.log(object);

查看更多
登录 后发表回答