Java中是否有var_dump(PHP)的等效项?


258

我们需要查看对象在Javascript中具有哪些方法/字段。


3
部分取决于您要如何打印它,但这是一个非常不错的实现,它返回一些HTML,然后可以将它们附加到文档中(或写入debugdiv):james.padolsey.com/javascript/prettyprint-for- javascript
Alex Vidal

我创建了一个JavaScript代码,其格式类似于PHP的var_dump:rubsphp.blogspot.com/2011/03/vardump-para-javascript.html

1
我发现此代码段好得多,并在我的项目中使用了它:phpjs.org/functions/var_dump
Hafiz

我使用在此网站上找到的函数:theredpine.wordpress.com/2011/10/23/var_dump-for-javascript

Answers:


220

正如其他人所说,您可以使用Firebug,这将使您在Firefox上无后顾之忧。Chrome和Safari都具有内置的开发人员控制台,该界面与Firebug控制台的界面几乎相同,因此您的代码应可在这些浏览器上移植。对于其他浏览器,有Firebug Lite

如果您不适合使用Firebug,请尝试以下简单脚本:

function dump(obj) {
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }

    alert(out);

    // or, if you wanted to avoid alerts...

    var pre = document.createElement('pre');
    pre.innerHTML = out;
    document.body.appendChild(pre)
}

我建议不要提醒每个单独的属性:某些对象具有很多属性,您会整天都在那儿单击“确定”,“确定”,“确定”,“ O ...”寻找”。


6
我也建议不要这样做-坦率地说,我只使用console.debug。但我指出了循环的可能性-这取决于用户他们希望对每个属性进行处理
Ken

我已经使用Firebug已有一段时间了,但是我不了解Firebug Lite,感谢您指出。
codefin

@nickf,我可以要求您访问stackoverflow.com/questions/9192990/…吗?不要知道这样的评论请求是否可以接受。
Istiaque Ahmed

我认为在stackoverflow.com/a/11315561/1403755上存在此功能的更强大版本,该版本实质上是php的print_r的副本
TorranceScott 2014年

108

如果您使用的是firefox,则firebug插件控制台是检查对象的绝佳方法

console.debug(myObject);

或者,您可以像这样遍历属性(包括方法):

for (property in object) {
    // do what you want with property, object[property].value
}

1
我喜欢这种方法,因为我只需要输入几个字节即可。我经常使用它。
userBG 2011年

这也适用于开发本机应用程序-喜欢它!
luk2302 '16

59

许多现代浏览器都支持以下语法:

JSON.stringify(myVar);

5
当接收圆形结构而不是防止它们时,它将引发异常。
郊狼2012年

console.选项一样,它仅显示变量的内容,不标记变量,因此,如果转储一堆变量,则必须手动标记每个变量。:-(
Synetech '19

27

不能这么说,您可以为此使用console.debug(object)。如果您这样做是为了维持生活,这项技术实际上每年可以为您节省数百小时:p


2
棒极了。今天以前我从未听说过console.debug(object),它为我节省了三天的时间,节省了大量的时间。用了20分钟,我把它修好了。谢谢!
ShiningLight

如果它实际上显示变量的名称而不是仅显示变量的内容,那会更好,这样您就可以同时看到一堆变量,而不必手动标记所有变量。¬_¬
Synetech

@Synetech试试console.debug({object})。如果您需要多个:console.debug({object1, object2})
SEoF

10

为了从问题标题的上下文中回答问题,这里有一个函数类似于PHP var_dump。它每次调用仅转储一个变量,但是它指示数据类型和值,并遍历数组和对象(即使它们是对象数组,反之亦然)。我相信这可以改善。我更像一个PHP家伙。

/**
 * Does a PHP var_dump'ish behavior.  It only dumps one variable per call.  The
 * first parameter is the variable, and the second parameter is an optional
 * name.  This can be the variable name [makes it easier to distinguish between
 * numerious calls to this function], but any string value can be passed.
 * 
 * @param mixed var_value - the variable to be dumped
 * @param string var_name - ideally the name of the variable, which will be used 
 *       to label the dump.  If this argumment is omitted, then the dump will
 *       display without a label.
 * @param boolean - annonymous third parameter. 
 *       On TRUE publishes the result to the DOM document body.
 *       On FALSE a string is returned.
 *       Default is TRUE.
 * @returns string|inserts Dom Object in the BODY element.
 */
function my_dump (var_value, var_name)
{
    // Check for a third argument and if one exists, capture it's value, else
    // default to TRUE.  When the third argument is true, this function
    // publishes the result to the document body, else, it outputs a string.
    // The third argument is intend for use by recursive calls within this
    // function, but there is no reason why it couldn't be used in other ways.
    var is_publish_to_body = typeof arguments[2] === 'undefined' ? true:arguments[2];

    // Check for a fourth argument and if one exists, add three to it and
    // use it to indent the out block by that many characters.  This argument is
    // not intended to be used by any other than the recursive call.
    var indent_by = typeof arguments[3] === 'undefined' ? 0:arguments[3]+3;

    var do_boolean = function (v)
    {
        return 'Boolean(1) '+(v?'TRUE':'FALSE');
    };

    var do_number = function(v)
    {
        var num_digits = (''+v).length;
        return 'Number('+num_digits+') '+v;
    };

    var do_string = function(v)
    {
        var num_chars = v.length;
        return 'String('+num_chars+') "'+v+'"';
    };

    var do_object = function(v)
    {
        if (v === null)
        {
            return "NULL(0)";
        }

        var out = '';
        var num_elem = 0;
        var indent = '';

        if (v instanceof Array)
        {
            num_elem = v.length;
            for (var d=0; d<indent_by; ++d)
            {
                indent += ' ';
            }
            out = "Array("+num_elem+") \n"+(indent.length === 0?'':'|'+indent+'')+"(";
            for (var i=0; i<num_elem; ++i)
            {
                out += "\n"+(indent.length === 0?'':'|'+indent)+"|   ["+i+"] = "+my_dump(v[i],'',false,indent_by);
            }
            out += "\n"+(indent.length === 0?'':'|'+indent+'')+")";
            return out;
        }
        else if (v instanceof Object)
        {
            for (var d=0; d<indent_by; ++d)
            {
                indent += ' ';
            }
            out = "Object \n"+(indent.length === 0?'':'|'+indent+'')+"(";
            for (var p in v)
            {
                out += "\n"+(indent.length === 0?'':'|'+indent)+"|   ["+p+"] = "+my_dump(v[p],'',false,indent_by);
            }
            out += "\n"+(indent.length === 0?'':'|'+indent+'')+")";
            return out;
        }
        else
        {
            return 'Unknown Object Type!';
        }
    };

    // Makes it easier, later on, to switch behaviors based on existance or
    // absence of a var_name parameter.  By converting 'undefined' to 'empty 
    // string', the length greater than zero test can be applied in all cases.
    var_name = typeof var_name === 'undefined' ? '':var_name;
    var out = '';
    var v_name = '';
    switch (typeof var_value)
    {
        case "boolean":
            v_name = var_name.length > 0 ? var_name + ' = ':''; // Turns labeling on if var_name present, else no label
            out += v_name + do_boolean(var_value);
            break;
        case "number":
            v_name = var_name.length > 0 ? var_name + ' = ':'';
            out += v_name + do_number(var_value);
            break;
        case "string":
            v_name = var_name.length > 0 ? var_name + ' = ':'';
            out += v_name + do_string(var_value);
            break;
        case "object":
            v_name = var_name.length > 0 ? var_name + ' => ':'';
            out += v_name + do_object(var_value);
            break;
        case "function":
            v_name = var_name.length > 0 ? var_name + ' = ':'';
            out += v_name + "Function";
            break;
        case "undefined":
            v_name = var_name.length > 0 ? var_name + ' = ':'';
            out += v_name + "Undefined";
            break;
        default:
            out += v_name + ' is unknown type!';
    }

    // Using indent_by to filter out recursive calls, so this only happens on the 
    // primary call [i.e. at the end of the algorithm]
    if (is_publish_to_body  &&  indent_by === 0)
    {
        var div_dump = document.getElementById('div_dump');
        if (!div_dump)
        {
            div_dump = document.createElement('div');
            div_dump.id = 'div_dump';

            var style_dump = document.getElementsByTagName("style")[0];
            if (!style_dump)
            {
                var head = document.getElementsByTagName("head")[0];
                style_dump = document.createElement("style");
                head.appendChild(style_dump);
            }
            // Thank you Tim Down [http://stackoverflow.com/users/96100/tim-down] 
            // for the following addRule function
            var addRule;
            if (typeof document.styleSheets != "undefined" && document.styleSheets) {
                addRule = function(selector, rule) {
                    var styleSheets = document.styleSheets, styleSheet;
                    if (styleSheets && styleSheets.length) {
                        styleSheet = styleSheets[styleSheets.length - 1];
                        if (styleSheet.addRule) {
                            styleSheet.addRule(selector, rule)
                        } else if (typeof styleSheet.cssText == "string") {
                            styleSheet.cssText = selector + " {" + rule + "}";
                        } else if (styleSheet.insertRule && styleSheet.cssRules) {
                            styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
                        }
                    }
                };
            } else {
                addRule = function(selector, rule, el, doc) {
                    el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
                };
            }

            // Ensure the dump text will be visible under all conditions [i.e. always
            // black text against a white background].
            addRule('#div_dump', 'background-color:white', style_dump, document);
            addRule('#div_dump', 'color:black', style_dump, document);
            addRule('#div_dump', 'padding:15px', style_dump, document);

            style_dump = null;
        }

        var pre_dump = document.getElementById('pre_dump');
        if (!pre_dump)
        {
            pre_dump = document.createElement('pre');
            pre_dump.id = 'pre_dump';
            pre_dump.innerHTML = out+"\n";
            div_dump.appendChild(pre_dump);
            document.body.appendChild(div_dump);
        }  
        else
        {
            pre_dump.innerHTML += out+"\n";
        }
    }
    else
    {
        return out;
    }
}

7

firebug或google-chrome网络检查器中的console.dir(指向链接页面的底部)将输出一个对象属性的交互式列表。

另请参阅此Stack-O答案


太糟糕了,它实际上并没有标记它。它仅显示其值,如果您想查看一堆变量,则无济于事。:-|
Synetech

7

您想以JSON形式查看整个对象(对象和变量内部的所有嵌套级别)。JSON代表JavaScript Object Notation,并且打印出对象的JSON字符串等效于var_dump(获取JavaScript对象的字符串表示形式)。幸运的是,JSON非常易于在代码中使用,并且JSON数据格式也很容易被人阅读。

例:

var objectInStringFormat = JSON.stringify(someObject);
alert(objectInStringFormat);

6

如果使用Firebug,则可以使用console.log输出对象,并在控制台中获取超链接的可探索项目。


问题在于它不标记变量,因此,如果转储一堆变量,则必须手动标记所有变量以区分它们。:-\
Synetech '19

4

对于那些不知道传入的变量类型的用户,对nickf函数进行了一些改进:

function dump(v) {
    switch (typeof v) {
        case "object":
            for (var i in v) {
                console.log(i+":"+v[i]);
            }
            break;
        default: //number, string, boolean, null, undefined 
            console.log(typeof v+":"+v);
            break;
    }
}

4

我改进了nickf的答案,因此它以递归方式遍历对象:

function var_dump(obj, element)
{
    var logMsg = objToString(obj, 0);
    if (element) // set innerHTML to logMsg
    {
        var pre = document.createElement('pre');
        pre.innerHTML = logMsg;
        element.innerHTML = '';
        element.appendChild(pre);
    }
    else // write logMsg to the console
    {
        console.log(logMsg);
    }
}

function objToString(obj, level)
{
    var out = '';
    for (var i in obj)
    {
        for (loop = level; loop > 0; loop--)
        {
            out += "    ";
        }
        if (obj[i] instanceof Object)
        {
            out += i + " (Object):\n";
            out += objToString(obj[i], level + 1);
        }
        else
        {
            out += i + ": " + obj[i] + "\n";
        }
    }
    return out;
}

4
console.log(OBJECT|ARRAY|STRING|...);
console.info(OBJECT|ARRAY|STRING|...);
console.debug(OBJECT|ARRAY|STRING|...);
console.warn(OBJECT|ARRAY|STRING|...);
console.assert(Condition, 'Message if false');

它们应该可以在Google Chrome和Mozilla Firefox上正常工作(如果您使用的是旧版的firefox,则必须安装Firebug插件)
在Internet Explorer 8或更高版本上,您必须执行以下操作:

  • 通过单击F12按钮启动“开发人员工具
  • 在选项卡列表中,单击“脚本”选项卡”
  • 单击右侧的“控制台”按钮

有关更多信息,您可以访问以下URL:https : //developer.chrome.com/devtools/docs/console-api


4

您可以简单地使用NPM包var_dump

npm install var_dump --save-dev

用法:

const var_dump = require('var_dump')

var variable = {
  'data': {
    'users': {
      'id': 12,
      'friends': [{
        'id': 1,
        'name': 'John Doe'
      }]
    }
  }
}

// print the variable using var_dump
var_dump(variable)

这将打印:

object(1) {
    ["data"] => object(1) {
        ["users"] => object(2) {
            ["id"] => number(12)
            ["friends"] => array(1) {
                [0] => object(2) {
                    ["id"] => number(1)
                    ["name"] => string(8) "John Doe"
                }
            }
        }
    }
}

链接:https//www.npmjs.com/package/@smartankur4u/vardump

晚点再谢我!



2

我使用了第一个答案,但我觉得其中缺少递归。

结果是这样的:

function dump(obj) {
    var out = '';
    for (var i in obj) {
        if(typeof obj[i] === 'object'){
            dump(obj[i]);
        }else{
            out += i + ": " + obj[i] + "\n";
        }
    }

    var pre = document.createElement('pre');
    pre.innerHTML = out;
    document.body.appendChild(pre);
}

2

基于此帖子中以前的功能。添加了递归模式和缩进。

function dump(v, s) {
  s = s || 1;
  var t = '';
  switch (typeof v) {
    case "object":
      t += "\n";
      for (var i in v) {
        t += Array(s).join(" ")+i+": ";
        t += dump(v[i], s+3);
      }
      break;
    default: //number, string, boolean, null, undefined 
      t += v+" ("+typeof v+")\n";
      break;
  }
  return t;
}

var a = {
  b: 1,
  c: {
    d:1,
    e:2,
    d:3,
    c: {
      d:1,
      e:2,
      d:3
    }
  }
};

var d = dump(a);
console.log(d);
document.getElementById("#dump").innerHTML = "<pre>" + d + "</pre>";

结果

b: 1 (number)
c: 
   d: 3 (number)
   e: 2 (number)
   c: 
      d: 3 (number)
      e: 2 (number)

这样做很好,但是最好显示变量的名称(例如在PHP中),这样您就可以区分多个变量而不必手动标记它们。
Synetech

0

以下是我最喜欢的Javascript 等同于PHP的var_dump / print_rvar_dump

 function dump(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;

  //The padding given at the beginning of the line.
  var level_padding = "";
  for(var j=0;j<level+1;j++) level_padding += "    ";

  if(typeof(arr) == 'object') { //Array/Hashes/Objects 
   for(var item in arr) {
    var value = arr[item];

    if(typeof(value) == 'object') { //If it is an array,
     dumped_text += level_padding + "'" + item + "' ...\n";
     dumped_text += dump(value,level+1);
    } else {
     dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
    }
   }
  } else { //Stings/Chars/Numbers etc.
   dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
 }

0

游戏晚了,但是这是一个非常方便的函数,使用起来非常简单,它允许您传递任意数量的任意类型的参数,并在浏览器控制台窗口中显示对象内容,就像调用控制台一样。从JavaScript登录-但是从PHP登录

请注意,您也可以通过传递“ TAG-YourTag”来使用标签,它将一直应用到读取另一个标签,例如“ TAG-YourNextTag”

/*
*   Brief:          Print to console.log() from PHP
*   Description:    Print as many strings,arrays, objects, and other data types to console.log from PHP.
*                   To use, just call consoleLog($data1, $data2, ... $dataN) and each dataI will be sent to console.log - note that
*                   you can pass as many data as you want an this will still work.
*
*                   This is very powerful as it shows the entire contents of objects and arrays that can be read inside of the browser console log.
*                   
*                   A tag can be set by passing a string that has the prefix TAG- as one of the arguments. Everytime a string with the TAG- prefix is
*                   detected, the tag is updated. This allows you to pass a tag that is applied to all data until it reaches another tag, which can then
*                   be applied to all data after it.
*
*                   Example:
*                   consoleLog('TAG-FirstTag',$data,$data2,'TAG-SecTag,$data3); 
*                   Result:
*                       FirstTag '...data...'
*                       FirstTag '...data2...'
*                       SecTag   '...data3...' 
*/
function consoleLog(){
    if(func_num_args() == 0){
        return;
    }

    $tag = '';
    for ($i = 0; $i < func_num_args(); $i++) {
        $arg = func_get_arg($i);
        if(!empty($arg)){       
            if(is_string($arg)&& strtolower(substr($arg,0,4)) === 'tag-'){
                $tag = substr($arg,4);
            }else{      
                $arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
                echo "<script>console.log('".$tag." ".$arg."');</script>";
            }       
        }
    }
}

注意:func_num_args()func_num_args()是php函数,用于读取动态数量的输入args,并允许此函数从一个函数调用中获取无限多个console.log请求

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.