programing

Javascript에 var_dump(PHP)와 동등한 것이 있습니까?

bestcode 2022. 11. 6. 10:32
반응형

Javascript에 var_dump(PHP)와 동등한 것이 있습니까?

Javascript에서 객체에 어떤 메서드/필드가 있는지 확인해야 합니다.

다른 사람들이 말한 것처럼 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], [Dammit that is I wanted property]를 클릭하면 하루 종일 표시됩니다.

Firefox를 사용하는 경우 Firebug 플러그인 콘솔은 개체를 검사하는 데 매우 적합합니다.

console.debug(myObject);

또는 다음과 같이 속성(메서드 포함)을 루프할 수 있습니다.

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

최신 브라우저의 대부분은 다음 구문을 지원합니다.

JSON.stringify(myVar);

이 경우 console.debug(개체)를 사용할 수 있을 정도로 충분히 명시되어 있지 않습니다.이 기술은 생계를 위해 이것을 한다면 말 그대로 1년에 수백 시간을 절약할 수 있습니다.p

이 질문의 제목 컨텍스트에서 질문에 답하기 위해 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;
    }
}

JSON JavaScript Object Notation합니다.var_dump(JavaScript 객 ( ( ( ( ( ( ( ( ( ( ( ( ( ( ().다행히 JSON은 코드 사용이 매우 용이하며 JSON 데이터 형식도 사람이 읽을 수 있습니다.

예:

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

firebug 또는 Google 웹 브라우저의 console.displays(링크된 페이지 하단에 표시)는 객체의 속성을 인터랙티브하게 출력합니다.

이 Stack-O 답변도 참조하십시오.

Firebug를 사용하는 경우 console.log를 사용하여 개체를 출력하고 콘솔에서 하이퍼링크된 탐색 가능한 항목을 가져올 수 있습니다.

들어오는 변수의 유형을 모르는 사람들을 위해 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;
    }
}

니크의 답변을 개선해서 물체를 통해 반복 루프되도록 했습니다.

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;
}
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

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

나중에 고마워!

JS에서 변환된 PHP 함수를 찾는 경우 http://phpjs.org라는 작은 사이트가 있습니다.거기서 PHP 함수의 대부분을 JS로 신뢰성 있게 쓸 수 있습니다.var_download try: http://phpjs.org/functions/var_dump/ (최상위 코멘트를 확인해 주세요.이것은 같은 사이트에서 다운로드 할 수도 있는 「download」에 의존합니다)

첫 번째 답을 사용했지만, 재귀가 빠진 것 같았어요.

결과는 다음과 같습니다.

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);
}

이 투고에 기재되어 있는 이전의 기능에 근거하고 있습니다.재귀 모드 및 들여쓰기가 추가되었습니다.

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)

을 사용하다은 '아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아,var_dump네스트된 오브젝트/패킷을 사용할 수 있습니다.여러 인수를 지원하지 않습니다.

function var_dump(variable) {
  let out = "";
  
  let type = typeof variable;
  if(type == "object") {
    var realType;
    var length;
    if(variable instanceof Array) {
      realType = "array";
      length = variable.length;
    } else {
      realType = "object";
      length = Object.keys(variable).length;
    }
    out = `${realType}(${length}) {`;
      for (const [key, value] of Object.entries(variable)) {
    out += `\n [${key}]=>\n ${var_dump(value).replace(/\n/g, "\n  ")}\n`;
  }
  out += "}";
  } else if(type == "string") {
    out = `${type}(${type.length}) "${variable}"`;
  } else {
    out = `${type}(${variable.toString()})`;
  }
  return out;
}
console.log(var_dump(1.5));
console.log(var_dump("Hello!"));
console.log(var_dump([]));
console.log(var_dump([1,2,3,[1,2]]));

console.log(var_dump({"a":"b"}));

게임 시작은 늦었지만, 여기 매우 사용하기 쉬운 함수가 있습니다.사용은 매우 간단하며, 임의의 유형의 인수를 원하는 만큼 전달할 수 있으며, 마치 자바스크립트에서 console.log를 호출한 것처럼 브라우저 콘솔 창에 오브젝트 내용을 표시할 수 있습니다.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()는 동적 수의 입력 Arg를 읽기 위한 php 함수이며, 이 함수는 하나의 함수 호출에서 무한히 많은 console.log 요구를 가질 수 있습니다.

다음은 Javascript에서 PHP에 해당하는 var_dump/print_r을 가장 좋아합니다.var_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;
}

console.log에 대해 비교적 중요한 내용을 추가하고 싶습니다.

대형 변수(대형 오디오 또는 비디오 데이터 버퍼 등)를 디버깅하는 경우.console.log(big_variable)를 인쇄하면 콘솔은 일부만 표시합니다(조금 분명합니다).

단, 변수가 루프 상태이고 이 변수가 계속 변경되는 경우, "클립보드에 복사"할 경우 브라우저는 변수를 다시 입력하도록 요구합니다(복사할 때 변경되었을 수 있습니다.

내 이야기를 들려줄게.저는 8192사이즈의 Float32array로 큰 오디오 데이터를 처리하는 앱을 프로그래밍하고 있습니다.버퍼에 특정 특성이 있는 경우 console.log()를 사용하여 변수를 인쇄한 후 해당 변수를 잡고 테스트 및 장난을 칩니다(또한 자동 테스트를 수행할 수 있도록 mock에도 사용합니다).

하지만, 결과는 결코 지속되지 않을 것이다.마이크가 오디오 데이터를 캡처해서 여기에 저장합니다.오디오 버퍼 변수와 모든 것이 작동하지만 console.log에서 정확한 변수를 복사하여 자동 테스트를 실행하는 모의 테스트를 수행하게 하면 동작이 극적으로 변경됩니다.

디버거에서 console.log에 표시된 변수를 복사하지 않고 "복사" 또는 "변수를 글로벌하게 설정"할 때마다 jsvm이 이를 요구하는 것으로 보입니다.오디오 버퍼가 다시 켜졌다.이 변수가 루프 내부에서 사용되고 있기 때문에 마이크는 녹음을 계속하고 오디오 버퍼가 원래 있던 것과 전혀 다른 사운드 어레이를 얻을 수 있었습니다.

오디오 또는 비디오 파일, 이미지 파일 등 복잡한 대규모 데이터 구조를 취급하는 경우...또한 이러한 값은 크롬 /firefox / 엣지 콘솔에서 읽을 때 변경될 수 있습니다.console.log(변수)가 아니라 console.log(JSON.stringify(변수))를 사용하십시오.그러면 시간을 많이 절약할 수 있을 거야

언급URL : https://stackoverflow.com/questions/323517/is-there-an-equivalent-for-var-dump-php-in-javascript

반응형