มีค่าเทียบเท่าสำหรับ var_dump (PHP) ใน Javascript หรือไม่


258

เราจำเป็นต้องดูว่ามีวิธีการ / ฟิลด์วัตถุใน Javascript


3
ส่วนหนึ่งขึ้นอยู่กับว่าคุณต้องการพิมพ์อย่างไร แต่นี่เป็นการใช้งานที่ดีมากที่ส่งคืน HTML บางส่วนที่คุณสามารถผนวกเข้ากับเอกสารของคุณ (หรือเขียนถึงdebugdiv): james.padolsey.com/javascript/prettyprint-for- javascript
Alex Vidal

ฉันสร้างรหัส JavaScript ที่จัดรูปแบบผลลัพธ์เช่น var_dump ของ PHP: rubsphp.blogspot.com/2011/03/vardump-para-javascript.html

1
ฉันพบข้อมูลโค้ดนี้ดีขึ้นมากและฉันใช้สิ่งนี้ในโครงการของฉัน: phpjs.org/functions/var_dump:604
Hafiz

ฉันใช้ฟังก์ชั่นที่พบในเว็บไซต์นี้: theredpine.wordpress.com/2011/10/23/var_dump-for-javascript

คำตอบ:


220

อย่างที่คนอื่นพูดคุณสามารถใช้ 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)
}

ฉันขอแนะนำให้ต่อต้านการแจ้งเตือนแต่ละคุณสมบัติ: วัตถุบางอย่างมีคุณสมบัติมากมายและคุณจะอยู่ที่นั่นตลอดทั้งวันคลิกที่ "ตกลง", "ตกลง", "ตกลง", "ตกลง ... " นั่นคือคุณสมบัติที่ฉันเป็น กำลังมองหา".


6
ฉันขอแนะนำต่อมันเช่นกัน - ตรงไปตรงมาฉันเพียงแค่ใช้ console.debug แต่ฉันได้ชี้ให้เห็นถึงความเป็นไปได้ของการวนซ้ำ - มันขึ้นอยู่กับผู้ใช้ว่าพวกเขาต้องการทำอะไรกับทรัพย์สินแต่ละอย่าง
Ken

ฉันใช้ firebug มาระยะหนึ่งแล้ว แต่ไม่รู้ Firebug Lite ขอบคุณที่ชี้ให้เห็น
codefin

@nickf ฉันขอให้คุณเยี่ยมชมได้ที่stackoverflow.com/questions/9192990/หรือไม่? ไม่ทราบว่าคำขอในความคิดเห็นนั้นเป็นที่ยอมรับหรือไม่
Istiaque Ahmed

ฉันคิดว่ารุ่นนี้มีฟังก์ชั่นการใช้งานที่แข็งแกร่งกว่าเล็กน้อยที่stackoverflow.com/a/11315561/1403755ซึ่งโดยพื้นฐานแล้วจะเหมือนกับ print_r สำหรับ php
TorranceScott

108

หากคุณใช้ firefox คอนโซลปลั๊กอิน firebugเป็นวิธีที่ยอดเยี่ยมในการตรวจสอบวัตถุ

console.debug(myObject);

หรือคุณสามารถวนซ้ำคุณสมบัติ (รวมถึงวิธีการ) ดังนี้:

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

1
ฉันชอบวิธีนี้เพราะฉันต้องการพิมพ์เพียงไม่กี่ไบต์ ฉันใช้มันบ่อยๆ
userBG

ใช้งานได้เมื่อพัฒนาแอปที่ตอบสนองพื้นเมืองเช่นกัน - รักเลย!
luk2302

59

เบราว์เซอร์สมัยใหม่จำนวนมากรองรับไวยากรณ์ต่อไปนี้:

JSON.stringify(myVar);

5
มันยิงข้อยกเว้นเมื่อได้รับโครงสร้างแบบวงกลมแทนที่จะป้องกันพวกมัน
โคโยตี้

เช่นเดียวกับconsole.ตัวเลือกสิ่งนี้จะแสดงเฉพาะเนื้อหาของตัวแปรเท่านั้นมันไม่ได้ติดป้ายตัวแปรดังนั้นหากคุณถ่ายโอนตัวแปรจำนวนมากคุณต้องติดป้ายกำกับแต่ละรายการด้วยตนเอง :-(
Synetech

27

ไม่สามารถระบุได้เพียงพอที่คุณสามารถใช้ console.debug (วัตถุ) สำหรับสิ่งนี้ เทคนิคนี้จะช่วยให้คุณประหยัดอย่างแท้จริงหลายร้อยชั่วโมงต่อปีหากคุณทำเพื่อหาเลี้ยงชีพ: p


2
ที่น่าตื่นตาตื่นใจ. ฉันไม่เคยได้ยินชื่อ console.debug (วัตถุ) มาก่อนและมันช่วยฉันได้หลายครั้งในรูปแบบที่ฉันต้องดิ้นรนเป็นเวลาสามวัน ภายใน 20 นาทีฉันได้รับการแก้ไขแล้ว ขอบคุณ!
ShiningLight

มันจะดีกว่าถ้ามันแสดงชื่อของตัวแปรแทนที่จะเป็นเพียงเนื้อหาของมันเพื่อให้คุณสามารถเห็นกลุ่มของตัวแปรในเวลาเดียวกันโดยไม่ต้องติดฉลากทั้งหมดด้วยตนเอง ¬_¬
Synetech

@Synetech console.debug({object})ลอง console.debug({object1, object2})หากคุณต้องการหลาย
SEoF

10

เพื่อตอบคำถามจากบริบทของชื่อของคำถามนี้นี่คือฟังก์ชั่นที่ทำสิ่งที่คล้ายกับ 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;
    }
}

7

console.dir (ไปที่ด้านล่างของหน้าเชื่อมโยง) ใน firebug หรือ google-chrome web-inspector จะส่งออกรายการแบบโต้ตอบของคุณสมบัติของวัตถุ

ดูเพิ่มเติมที่คำตอบ Stack-O นี้


น่าเสียดายที่มันไม่ติดฉลาก มันแสดงเฉพาะค่าที่ไม่ช่วยถ้าคุณต้องการเห็นตัวแปรจำนวนมาก : - |
Synetech

7

คุณต้องการที่จะเห็นวัตถุทั้งหมด (ระดับที่ซ้อนกันของวัตถุและตัวแปรภายในมัน) ในรูปแบบ JSON JSON ย่อมาจาก JavaScript Object Notation และการพิมพ์สตริง JSON ของวัตถุของคุณเป็นสิ่งที่ดีเทียบเท่าvar_dump(เพื่อรับการแสดงสตริงของวัตถุ JavaScript) โชคดีที่ JSON นั้นใช้งานง่ายในโค้ดและรูปแบบข้อมูล JSON นั้นค่อนข้างมนุษย์สามารถอ่านได้

ตัวอย่าง:

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

6

ถ้าคุณใช้ Firebug คุณสามารถใช้console.logเพื่อเอาท์พุทวัตถุและรับไอเท็มไฮเปอร์ลิงก์ที่สามารถอธิบายได้ในคอนโซล


ปัญหาเกี่ยวกับสิ่งนี้คือมันไม่ติดเลเบลของตัวแปรดังนั้นหากคุณดัมพ์ตัวแปรจำนวนมากคุณต้องติดเลเบลตัวแปรทั้งหมดด้วยตนเองเพื่อแยกแยะตัวแปร : - \
Synetech

4

การปรับปรุงฟังก์ชั่นของ 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;
    }
}

4

ฉันปรับปรุงคำตอบของ nickf ดังนั้นมันวนซ้ำผ่านวัตถุ:

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

สิ่งเหล่านี้ควรทำงานได้อย่างถูกต้องบน Google Chrome และ Mozilla Firefox (หากคุณใช้ Firefox รุ่นเก่าดังนั้นคุณต้องติดตั้งปลั๊กอิน Firebug)
บน Internet Explorer 8 ขึ้นไปคุณต้องทำดังนี้:

  • เปิด "เครื่องมือสำหรับนักพัฒนาโดยคลิกที่ปุ่ม F12
  • ในรายการแท็บคลิกที่ "สคริปต์" แท็บ "
  • คลิกที่ปุ่ม "คอนโซล" ทางด้านขวา

สำหรับข้อมูลเพิ่มเติมคุณสามารถเยี่ยมชม URL นี้: https://developer.chrome.com/devtools/docs/console-api


4

คุณสามารถใช้แพคเกจ 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

ขอบคุณฉันในภายหลัง!


3

หากคุณกำลังมองหาฟังก์ชัน PHP แปลงใน JS มีเว็บไซต์เล็ก ๆ นี้: http://phpjs.org ที่นั่นคุณจะได้รับประโยชน์สูงสุดจากฟังก์ชั่น PHP ที่เขียนได้อย่างน่าเชื่อถือใน JS สำหรับ var_dump ลอง: http://phpjs.org/functions/var_dump/ (ตรวจสอบให้แน่ใจว่ามีการแสดงความคิดเห็นด้านบนนี้ขึ้นอยู่กับ "echo" ซึ่งสามารถดาวน์โหลดได้จากเว็บไซต์เดียวกัน)


2

ฉันใช้คำตอบแรก แต่ฉันรู้สึกว่าขาดการสอบถามซ้ำ

ผลที่ได้คือ:

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

ขึ้นอยู่กับฟังก์ชั่นก่อนหน้านี้ที่พบในโพสต์นี้ เพิ่มโหมดการเรียกซ้ำและการเยื้อง

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)

สิ่งนี้เป็นสิ่งที่ดี แต่มันจะดีกว่าถ้ามันแสดงชื่อของตัวแปร (เช่นใน PHP) เพื่อให้คุณสามารถแยกความแตกต่างของตัวแปรหลายตัวโดยไม่ต้องติดป้ายกำกับด้วยตนเอง
Synetech

0

ต่อไปนี้จะเป็นที่ชื่นชอบvar_dump / เทียบเท่า print_rในจาวาสคริปต์เพื่อ var_dumpPHPs

 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

มาถึงช่วงท้ายเกม แต่นี่เป็นฟังก์ชั่นที่ใช้งานง่ายมากที่ใช้งานง่ายมากช่วยให้คุณสามารถส่งอาร์กิวเมนต์ได้มากเท่าที่คุณต้องการและจะแสดงเนื้อหาของวัตถุในหน้าต่างคอนโซลของเบราว์เซอร์เสมือนว่าคุณเรียกคอนโซล บันทึกจาก JavaScript - แต่มาจาก 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 ()เป็นฟังก์ชั่น php สำหรับการอ่านจำนวน args อินพุตแบบไดนามิกและอนุญาตให้ฟังก์ชันนี้มีการร้องขอ console.log จำนวนมากจากการเรียกฟังก์ชันหนึ่งครั้ง

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.