print_r(),JavaScript版

本文介绍了一种在JavaScript中实现类似PHP print_r功能的方法,能够优雅地解析并展示数组和对象的内容,支持HTML和纯文本格式输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

寻找JavaScript的print_r()吗? 别再看了! 最后,一种体面的方法来找出神秘的数组或对象中的内容!

请注意,此版本的print_r()依赖于(包括)getType(),该类型旨在以浏览器无关的方式检测JavaScript中的基本类型(不幸的是,

$ object.constructor.match()技巧不适用于Safari或IE)。

特别感谢以下TSDN成员,他们在此程序的开发过程中提供了宝贵的帮助,并深表感谢:

  • gits
  • iam_clint
  • 意志力
  • 紫色

<html>
    <head>
        <script type="text/javascript">
/**
*   getType
*
*   Use this when typeof returns 'Object'.
*
*   @param mixed $obj The object to investigrate.
*
*   @return string The object's constructor.
*
*   @author Josh Zerin, Life Blue Media (http://www.lifeblue.com/)
*   @author Special thanks to:
*       - gits
*       - iam_clint
*       - volectricity
*       - Purple
*   http://www.thescripts.com/
*/
function getType($obj)
{
    /***************
    *
    *   Two special cases:  undefined and null.
    */
    if( typeof $obj == 'undefined' )
    {
        return 'undefined';
    } 
    if($obj === null)
    {
        return 'null';
    } 
    /***************
    *
    *   Run through the standard constructors.
    */
    switch($obj.constructor)
    {
        case Array:
            return 'Array';
        case Boolean:
            return 'Boolean';
        case Date:
            return 'Date';
        case Error:
            return 'Error';
        case Function:
            return 'Function';
        case Number:
            return 'Number';
        case RegExp:
            return 'RegExp';
        case String:
            return 'String';
        default: 
            /***************
            *
            *   HTML Elements will have a nodeType property.  It is unlikely, though possible, that other objects will.
            */
            if( typeof($obj.nodeType) != 'undefined' )
            {
                return 'HTML ' + $obj.nodeName.toUpperCase() + ' Element';
            } 
            /***************
            *
            *   If it's not an HTML Element, it might be an Event.
            */
            if($obj.toString)
            {
                if($obj.toString().match('Event'))
                {
                    return 'Event';
                }
            } 
            /***************
            *
            *   I give up.
            */
            return 'Object';
    }
} 
/**
*
*   print_r
*
*   Similar to the PHP function of the same name, except it always returns its output (I never liked that about PHP's print_r()).
*
*   @param mixed $content The variable you're trying to print_r.  Generally an object or array.
*
*   @param bool $htmlEncode How to format the output:
*       - true:     Use <br /> for line breaks, and &nbsp; for tabs.
*       - false:    Use \n for line breaks and \t for tabs.
*
*   @param string $basePrefix The base prefix that will be appended to all lines of output.  Very useful if you need your debug output to all line up (and something that REALLY bugs me about PHP's print_r()!).
*
*   @param string $_prefix (internal)
*
*   @return string A print_r()'ed string, similar in format to the PHP function of the same name (but with a few enhancements ~_^).
*
*   @author Josh Zerin, Life Blue Media (http://www.lifeblue.com/)
*   @author Special thanks to:
*       - gits
*       - iam_clint
*       - volectricity
*       - Purple
*   http://www.thescripts.com/
*/
function print_r($content, $htmlEncode, $basePrefix, $_prefix)
{
    /***************
    *
    *   $_prefix must be a string.
    */
    if( ! $_prefix )
    {
        $_prefix = '';
    } 
    /***************
    *
    *   Set the $basePrefix if not already set.
    */
    if( ! $basePrefix )
    {
        $basePrefix =
        (
            // If $_prefix is defined, we'll just use that.
            $_prefix
                ? $_prefix
                :
                (
                    // Otherwise, use a default.
                    $htmlEncode
                        ? '&nbsp;&nbsp;&nbsp;&nbsp;'
                        : '\t'
                )
        );
    } 
    /***************
    *
    *   How do we display newlines?
    */
    var $newLine = ($htmlEncode ? '<br />' : '') + '\n'; 
    /***************
    *
    *   Init output string.
    */
    var $retVal = ''; 
    /****************
    *
    *   We don't need to redundantly output certain types (the 'value' of null & undefined are self-explanatory, and we auto-output the type of Array & Object, so we don't want to do it twice).
    */
    var $blacklistDisplayType =
    {
        'null':         true,
        'Array':        true,
        'Object':       true,
        'undefined':    true
    } 
    /***************
    *
    *   Begin processing $content.
    */
    var $myType = getType($content);
    var $subType = ''; 
    /***************
    *
    *   And off we go!
    */
    if( $myType == 'Array' )
    {
        // E.g., "Array:\n\t(\n"
        $retVal += $myType + ':' + $newLine + $_prefix + '(' + $newLine; 
        /***************
        *
        *   Save the closing format before we go modifying $_prefix.
        */
        var $close = $_prefix + ')' + $newLine; 
        /***************
        *
        *   $basePrefix is only for *child* elements of the array.
        */
        $_prefix += $basePrefix; 
        /***************
        *
        *   for...in not useful on Arrays, since that will also return member functions.
        */
        for( var $i = 0; $i < $content.length; ++$i )
        {
            var $innerType = getType($content[$i]); 
            // E.g., "\t\t0 => (Number) "
            $retVal += $_prefix + $i + ' => ' +
            (
                /***************
                *
                *   Should we display the type of the child element?
                */
                $blacklistDisplayType[$innerType]
                    ? ''
                    : ' (' + getType($content[$i]) + ')'
            ) + ' '; 
            /***************
            *
            *   If the child element has children of its own, recursively process them.
            */
            if(($innerType == 'Array') || ($innerType == 'Object'))
            {
                $retVal +=
                    print_r
                    (
                        $content[$i],
                        $htmlEncode,
                        $basePrefix,
                        $_prefix
                    );
            }
            else
            {
                $retVal += $content[$i] + $newLine;
            }
        } 
        // E.g., "\t)\n"
        $retVal += $close;
    }
    else if( $myType == 'Object' )
    {
        $retVal += $myType + ':' + $newLine + $_prefix + '(' + $newLine;
        var $close = $_prefix + ')' + $newLine;
        $_prefix += $basePrefix; 
        /***************
        *
        *   for not useful on Objects, since they generally have no length property.
        */
        for( $i in $content )
        {
            var $innerType = getType($content[$i]);
            $retVal += $_prefix + $i + ' => ' +
            (
                $blacklistDisplayType[$innerType]
                    ? ''
                    : ' (' + getType($content[$i]) + ')'
            ) + ' '; 
            if( ($innerType == 'Array') || ($innerType == 'Object') )
            {
                $retVal +=
                    print_r
                    (
                        $content[$i],
                        $htmlEncode,
                        $basePrefix,
                        $_prefix
                    );
            }
            else
            {
                $retVal += $content[$i] + $newLine;
            }
        } 
        $retVal += $close;
    }
    else
    {
        /***************
        *
        *   If it ain't an object, then it's scalar.
        */
        $retVal += $content;
    } 
    /***************
    *
    *   And we're done!
    */
    return $retVal;
}
        </script>
    </head> 
    <body>
        <script type="text/javascript">
        // <![CDATA[ 
            /*
                Desired output: 
                Object:
                (
                    Array => Array:
                    (
                        0 => (Number) 0
                        1 => (String) 1
                        2 => (Number) 2.3
                        3 => (String) Four
                        4 => Object:
                        (
                            Five => (Number) 5
                        )
                    )
                    Number => (Number) 1
                    Float => (Number) 2.3
                    String => (String) Four
                    Sub => Object:
                    (
                        empty => (Boolean) false
                    )
                    null => null
                    undef => undefined
                    Element => (HTML BODY Element) [object HTMLBodyElement]
                )
            */ 
            var $theObj = {
                'Array':    [
                    0, '1', 2.3, 'Four', { 'Five': 5 }
                ],
                'Number':   1,
                'Float':    2.3,
                'String':   'Four',
                'Sub':      {
                    'empty':    false
                },
                'null':     null,
                'undef':    undefined,
                'Element':  document.getElementsByTagName('body')[0]
            }; 
            document.write(print_r($theObj, true));
        // ]]>
        </script>
    </body>
</html> 
附加的文件
文件类型:zip print_r.html.zip (2.8 KB,276浏览)

From: https://bytes.com/topic/javascript/insights/701497-print_r-javascript-edition

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值