Javascript 中是否有 var_dump (PHP) 的等价物?

IT技术 php javascript
2021-01-25 20:22:17

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

6个回答

正如其他人所说,您可以使用 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)
}

我建议不要提醒每个单独的属性:有些对象有很多属性,你会整天在那里点击“确定”、“确定”、“确定”、“哦……该死的,这就是我的财产寻找”。

我认为stackoverflow.com/a/11315561/1403755存在此函数的稍微更强大的版本,它本质上是 php 的 print_r 的副本
2021-03-19 20:22:17
@nickf,我可以请您访问stackoverflow.com/questions/9192990/...吗?不知道这样的评论请求是否可以接受。
2021-04-08 20:22:17
我也建议反对它 - 坦率地说,我只会使用 console.debug。但我指出了循环的可能性 - 这取决于用户他们想对每个属性做什么
2021-04-09 20:22:17
我已经使用 firebug 一段时间了,但不知道 Firebug Lite,感谢您指出。
2021-04-11 20:22:17

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

console.debug(myObject);

或者,您可以循环遍历属性(包括方法),如下所示:

for (property in object) {
    // do what you want with property, object[property].value
}
这也适用于开发 react-native 应用程序 - 喜欢它!
2021-03-29 20:22:17
我喜欢这种方法,因为我只需要输入几个字节。我经常使用它。
2021-03-30 20:22:17

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

JSON.stringify(myVar);
console.选项一样,这里只显示变量的内容,不给变量打标签,所以如果你转储一堆变量,你必须手动标记每个变量。:-(
2021-03-22 20:22:17
它在接收圆形结构而不是防范它们时会触发异常。
2021-03-31 20:22:17

不能充分说明您可以为此使用 console.debug(object) 。如果您以此为生,这项技术每年将为您节省数百小时:p

@Synetech 试试console.debug({object})如果您需要多个:console.debug({object1, object2}).
2021-03-15 20:22:17
如果它实际上显示变量的名称而不是仅显示其内容会更好,这样您就可以同时看到一堆变量而无需手动标记所有变量。~~~
2021-03-16 20:22:17
太棒了。在今天之前,我从未听说过 console.debug(object) ,它为我已经苦苦挣扎了三天的表单为我节省了大量时间。用了 20 分钟,我把它修好了。谢谢!
2021-03-21 20:22:17

为了从这个问题标题的上下文中回答这个问题,这里有一个执行类似于 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;
    }
}