[javascript] Javascript에 var_dump (PHP)에 해당하는 것이 있습니까?

객체가 자바 스크립트에서 가지고있는 메소드 / 필드를 확인해야합니다.



답변

다른 사람들이 말했듯이 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)
}

각 개별 속성에 대해 경고하지 않는 것이 좋습니다. 일부 개체에는 많은 속성이 있으며 “OK”, “OK”, “OK”, “O …를 클릭하면 하루 종일있을 것입니다. 찾고있는”.


답변

firefox를 사용하는 경우 firebug 플러그인 콘솔은 객체를 검사하는 훌륭한 방법입니다.

console.debug(myObject);

또는 다음과 같이 속성 (메소드 포함)을 반복 할 수 있습니다.

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


답변

많은 최신 브라우저가 다음 구문을 지원합니다.

JSON.stringify(myVar);


답변

이것을 위해 console.debug (object)를 사용할 수 있다고 충분히 말할 수는 없습니다. 이 기술을 사용하면 생계를 위해이 작업을 수행하면 연간 수백 시간을 절약 할 수 있습니다.


답변

이 질문의 제목 맥락에서 질문에 대답하기 위해 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;
    }
}


답변

Firebug 또는 google-chrome 웹 검사기에서 console.dir (링크 된 페이지의 아래쪽으로)은 객체 속성의 대화식 목록을 출력합니다.

참조 이 스택-O 응답


답변

JSON 형식으로 전체 객체 (모든 중첩 된 수준의 객체 및 변수)를 JSON 형식으로 보려고합니다. JSON은 JavaScript Object Notation의 약자이며, 객체의 JSON 문자열을 인쇄하는 것은 var_dump(JavaScript 객체의 문자열 표현을 얻는 것과) 동등 합니다. 다행히 JSON은 코드에서 사용하기가 매우 쉽고 JSON 데이터 형식도 사람이 읽을 수 있습니다.

예:

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