Czy istnieje JavaScript dla var_dump (PHP)?


258

Musimy zobaczyć, jakie metody / pola ma obiekt w JavaScript.


3
Częściowo zależy to od tego, jak chcesz go wydrukować, ale jest to naprawdę fajna implementacja, która zwraca trochę HTML, który możesz następnie dołączyć do dokumentu (lub napisać do debugdiv): james.padolsey.com/javascript/prettyprint-for- javascript
— Alex Vidal

Tworzę kod JavaScript, który formatuje wynik, taki jak var_dump PHP: rubsphp.blogspot.com/2011/03/vardump-para-javascript.html

1
Fragment kodu znalazłem znacznie lepiej i używam go w swoich projektach: phpjs.org/functions/var_dump:604
— Hafiz

Korzystam z funkcji znalezionej na tej stronie: theredpine.wordpress.com/2011/10/23/var_dump-for-javascript

Odpowiedzi:


220

Jak powiedzieli inni, możesz użyć Firebug, a to rozwiąże problem bez obaw o Firefox. Chrome i Safari mają wbudowaną konsolę programisty, która ma prawie identyczny interfejs jak konsola Firebug, więc kod powinien być przenośny w tych przeglądarkach. W przypadku innych przeglądarek jest Firebug Lite .

Jeśli Firebug nie jest dla Ciebie opcją, spróbuj tego prostego skryptu:

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

Odradzam ostrzeganie o poszczególnych nieruchomościach: niektóre obiekty mają DUŻO właściwości i będziesz tam cały dzień, klikając „OK”, „OK”, „OK”, „O ... cholera, to była własność, którą byłem szukam ”.


6
Odradzałbym to również - szczerze mówiąc, po prostu używałbym konsoli.debug. Ale zwróciłem uwagę na możliwość zapętlenia - to od użytkownika zależy, co chce zrobić z każdą właściwością
— Ken

Od jakiegoś czasu używam Firebuga, ale nie wiedziałem o Firebug Lite, dziękuję za zwrócenie na to uwagi.
— codefin

@nickf, czy mogę poprosić o wizytę na stackoverflow.com/questions/9192990/... ? Nie wiadomo, czy taka prośba w komentarzu jest do przyjęcia.
— Istiaque Ahmed

Myślę, że nieco bardziej niezawodna wersja tej funkcji istnieje na stackoverflow.com/a/11315561/1403755, który jest w zasadzie duplikatem print_r dla php
— TorranceScott

108

Jeśli używasz firefox, konsola wtyczki firebug to doskonały sposób na badanie obiektów

console.debug(myObject);

Alternatywnie możesz przeglądać właściwości (w tym metody) w następujący sposób:

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

1
Uwielbiam tę metodę, ponieważ muszę wpisać tylko kilka bajtów. Często go używam.
— userBG

Działa to również podczas tworzenia aplikacji natywnych - uwielbiaj to!
— luk2302,

59

Wiele nowoczesnych przeglądarek obsługuje następującą składnię:

JSON.stringify(myVar);

5
Występuje wyjątek, gdy otrzymuje się okrągłe struktury zamiast się przed nimi chronić.
— Coyote

Podobnie jak console.opcje, pokazuje tylko zawartość zmiennej, nie oznacza jej zmiennej, więc jeśli zrzucisz kilka zmiennych, musisz ręcznie oznaczyć każdą z nich. :-(
— Synetech,

27

Nie można stwierdzić, że można do tego użyć konsoli.debug (obiekt). Ta technika pozwoli ci zaoszczędzić dosłownie setki godzin rocznie, jeśli będziesz to robić na życie: str


2
To jest wspaniałe. Nigdy wcześniej nie słyszałem o konsoli.debug (obiekcie) i dzięki temu zaoszczędziłem mnóstwo czasu na formie, z którą walczyłem od trzech dni. W ciągu 20 minut naprawiłem to. Dziękuję Ci!
— ShiningLight

Byłoby lepiej, gdyby faktycznie wyświetlała nazwę zmiennej, a nie tylko jej zawartość, aby można było zobaczyć kilka zmiennych jednocześnie bez konieczności ręcznego etykietowania ich wszystkich. ¬_¬
— Synetech,

@Synetech spróbuj console.debug({object}). Jeśli trzeba wiele: console.debug({object1, object2}).
— SEOF

10

Aby odpowiedzieć na pytanie z kontekstu tytułu tego pytania, oto funkcja, która robi coś podobnego do PHP var_dump. Zrzuca tylko jedną zmienną na każde wywołanie, ale wskazuje typ danych, a także wartość i iteruje tablice i obiekty [nawet jeśli są to tablice obiektów i odwrotnie]. Jestem pewien, że można to poprawić. Jestem bardziej facetem od 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

console.dir (w dolnej części połączonej strony) w Firebug lub w Google-Chrome Web-Inspector wyświetli interaktywną listę właściwości obiektu.

Zobacz także tę odpowiedź Stack-O


Szkoda, że ​​tak naprawdę nie oznacza tego; pokazuje tylko swoją wartość, co nie pomaga, jeśli chcesz zobaczyć kilka zmiennych. : - |
— Synetech

7

Chcesz zobaczyć cały obiekt (wszystkie zagnieżdżone poziomy obiektów i zmiennych w nim) w formie JSON. JSON oznacza JavaScript Object Notation, a wydrukowanie ciągu JSON obiektu jest dobrym odpowiednikiem var_dump(aby uzyskać ciąg reprezentujący obiekt JavaScript). Na szczęście JSON jest bardzo łatwy w użyciu w kodzie, a format danych JSON jest również bardzo czytelny dla człowieka.

Przykład:

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

6

Jeśli używasz Firebug, możesz użyć console.log, aby wyprowadzić obiekt i uzyskać w konsoli hiperłącza do eksploracji.


Problem polega na tym, że nie etykietuje zmiennej, więc jeśli zrzucisz kilka zmiennych, musisz ręcznie oznaczyć je wszystkie, aby je rozróżnić. : - \
— Synetech,

4

Trochę ulepszenia funkcji nickf dla tych, którzy nie znają typu zmiennej:

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

Poprawiłem odpowiedź nickf, więc rekurencyjnie zapętla się przez obiekty:

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

Powinny one działać poprawnie w przeglądarce Google Chrome i Mozilla Firefox (jeśli korzystasz ze starej wersji Firefoxa, więc musisz zainstalować wtyczkę Firebug)
W przeglądarce Internet Explorer 8 lub nowszej musisz wykonać następujące czynności:

  • Uruchom „Narzędzia programistyczne”, klikając przycisk F12
  • Na liście kart kliknij kartę „Skrypt”
  • Kliknij przycisk „Konsola” po prawej stronie

Aby uzyskać więcej informacji, możesz odwiedzić ten adres URL: https://developer.chrome.com/devtools/docs/console-api


4

Możesz po prostu użyć pakietu NPM var_dump

npm install var_dump --save-dev

Stosowanie:

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)

Spowoduje to wydrukowanie:

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

Link: https://www.npmjs.com/package/@smartankur4u/vardump

Podziękujesz mi później!



2

Użyłem pierwszej odpowiedzi, ale czułem, że brakuje w niej rekurencji.

Rezultat był następujący:

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

Na podstawie poprzednich funkcji znalezionych w tym poście. Dodano tryb rekurencyjny i wcięcia.

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

Przykład

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

Wynik

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

To dobrze, ale byłoby lepiej, gdyby pokazywał nazwę zmiennej (jak w PHP), abyś mógł rozróżnić wiele zmiennych bez konieczności ręcznego ich oznaczania.
— Synetech,

0

Oto mój ulubiony odpowiednik var_dump / print_r w JavaScript w PHP 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;
 }

0

Późno do gry, ale tutaj jest bardzo przydatna funkcja, która jest bardzo prosta w użyciu, pozwala przekazać dowolną liczbę argumentów, jak chcesz, i wyświetli zawartość obiektu w oknie konsoli przeglądarki tak, jakbyś nazwał konsolę. log z JavaScript - ale z PHP

Uwaga: możesz również używać tagów, przekazując „TAG-YourTag”, a będzie on stosowany, dopóki nie zostanie odczytany inny tag, na przykład „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>";
            }       
        }
    }
}

UWAGA: func_num_args () i func_num_args () są funkcjami php do odczytu dynamicznej liczby argumentów wejściowych i pozwalają tej funkcji na nieskończenie wiele żądań console.log z jednego wywołania funkcji

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.