What is the JavaScript equivalent of var_dump or p

2019-01-08 03:01发布

This question already has an answer here:

I would like to see the structure of object in JavaScript (for debugging). Is there anything similar to var_dump in PHP?

10条回答
够拽才男人
2楼-- · 2019-01-08 03:28

Most common way:

console.log(object);

However I must mention JSON.stringify which is useful to dump variables in non-browser scripts:

console.log( JSON.stringify(object) );

The JSON.stringify function also supports built-in prettification as pointed out by Simon Zyx.

Example:

var obj = {x: 1, y: 2, z: 3};

console.log( JSON.stringify(obj, null, 2) ); // spacing level = 2

The above snippet will print:

{
  "x": 1,
  "y": 2,
  "z": 3
}

On caniuse.com you can view the browsers that support natively the JSON.stringify function: http://caniuse.com/json

You can also use the Douglas Crockford library to add JSON.stringify support on old browsers: https://github.com/douglascrockford/JSON-js

Docs for JSON.stringify: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

I hope this helps :-)

查看更多
何必那么认真
3楼-- · 2019-01-08 03:28

A nice simple solution for parsing a JSON Response to HTML.

var json_response = jQuery.parseJSON(data);
html_response += 'JSON Response:<br />';

jQuery.each(json_response, function(k, v) {
    html_response += outputJSONReponse(k, v);
});

function outputJSONReponse(k, v) {
    var html_response = k + ': ';

    if(jQuery.isArray(v) || jQuery.isPlainObject(v)) {
        jQuery.each(v, function(j, w) {
            html_response += outputJSONReponse(j, w);
        });
    } else {
        html_response += v + '<br />';
    }

    return html_response;
}
查看更多
该账号已被封号
4楼-- · 2019-01-08 03:31

I wrote this JS function dump() to work like PHP's var_dump(). To show the contents of the variable in an alert window: dump(variable) To show the contents of the variable in the web page: dump(variable, 'body') To just get a string of the variable: dump(variable, 'none')

/* repeatString() returns a string which has been repeated a set number of times */ 
function repeatString(str, num) {
    out = '';
    for (var i = 0; i < num; i++) {
        out += str; 
    }
    return out;
}

/*
dump() displays the contents of a variable like var_dump() does in PHP. dump() is
better than typeof, because it can distinguish between array, null and object.  
Parameters:
  v:              The variable
  howDisplay:     "none", "body", "alert" (default)
  recursionLevel: Number of times the function has recursed when entering nested
                  objects or arrays. Each level of recursion adds extra space to the 
                  output to indicate level. Set to 0 by default.
Return Value:
  A string of the variable's contents 
Limitations:
  Can't pass an undefined variable to dump(). 
  dump() can't distinguish between int and float.
  dump() can't tell the original variable type of a member variable of an object.
  These limitations can't be fixed because these are *features* of JS. However, dump()
*/
function dump(v, howDisplay, recursionLevel) {
    howDisplay = (typeof howDisplay === 'undefined') ? "alert" : howDisplay;
    recursionLevel = (typeof recursionLevel !== 'number') ? 0 : recursionLevel;


    var vType = typeof v;
    var out = vType;

    switch (vType) {
        case "number":
            /* there is absolutely no way in JS to distinguish 2 from 2.0
            so 'number' is the best that you can do. The following doesn't work:
            var er = /^[0-9]+$/;
            if (!isNaN(v) && v % 1 === 0 && er.test(3.0))
                out = 'int';*/
        case "boolean":
            out += ": " + v;
            break;
        case "string":
            out += "(" + v.length + '): "' + v + '"';
            break;
        case "object":
            //check if null
            if (v === null) {
                out = "null";

            }
            //If using jQuery: if ($.isArray(v))
            //If using IE: if (isArray(v))
            //this should work for all browsers according to the ECMAScript standard:
            else if (Object.prototype.toString.call(v) === '[object Array]') {  
                out = 'array(' + v.length + '): {\n';
                for (var i = 0; i < v.length; i++) {
                    out += repeatString('   ', recursionLevel) + "   [" + i + "]:  " + 
                        dump(v[i], "none", recursionLevel + 1) + "\n";
                }
                out += repeatString('   ', recursionLevel) + "}";
            }
            else { //if object    
                sContents = "{\n";
                cnt = 0;
                for (var member in v) {
                    //No way to know the original data type of member, since JS
                    //always converts it to a string and no other way to parse objects.
                    sContents += repeatString('   ', recursionLevel) + "   " + member +
                        ":  " + dump(v[member], "none", recursionLevel + 1) + "\n";
                    cnt++;
                }
                sContents += repeatString('   ', recursionLevel) + "}";
                out += "(" + cnt + "): " + sContents;
            }
            break;
    }

    if (howDisplay == 'body') {
        var pre = document.createElement('pre');
        pre.innerHTML = out;
        document.body.appendChild(pre)
    }
    else if (howDisplay == 'alert') {
        alert(out);
    }

    return out;
}
查看更多
\"骚年 ilove
5楼-- · 2019-01-08 03:36

I put this forward to help anyone needing something readily practical for giving you a nice, prettified (indented) picture of a JS Node. None of the other solutions worked for me for a Node ("cyclical error" or whatever...). This walks you through the tree under the DOM Node (without using recursion) and gives you the depth, tagName (if applicable) and textContent (if applicable).

Any other details from the nodes you encounter as you walk the tree under the head node can be added as per your interest...

function printRNode( node ){
    // make sort of human-readable picture of the node... a bit like PHP print_r

    if( node === undefined || node === null ){
        throwError( 'node was ' + typeof node );
    }
    let s = '';

    // NB walkDOM could be made into a utility function which you could 
    // call with one or more callback functions as parameters...

    function walkDOM( headNode ){
      const stack = [ headNode ];
      const depthCountDowns = [ 1 ];
      while (stack.length > 0) {
        const node = stack.pop();
        const depth = depthCountDowns.length - 1;
        // TODO non-text, non-BR nodes could show more details (attributes, properties, etc.)
        const stringRep = node.nodeType === 3? 'TEXT: |' + node.nodeValue + '|' : 'tag: ' + node.tagName;
        s += '  '.repeat( depth ) + stringRep + '\n';
        const lastIndex = depthCountDowns.length - 1;
        depthCountDowns[ lastIndex ] = depthCountDowns[ lastIndex ] - 1;
        if( node.childNodes.length ){
            depthCountDowns.push( node.childNodes.length );
            stack.push( ... Array.from( node.childNodes ).reverse() );
        }
        while( depthCountDowns[ depthCountDowns.length - 1 ] === 0 ){
            depthCountDowns.splice( -1 );
        }
      }
    } 
    walkDOM( node );
    return s;
}
查看更多
对你真心纯属浪费
6楼-- · 2019-01-08 03:40

You could also try this function. Can't remember the original author, but all credits goes to him/her.

Works like a charm - 100% the same as var_dump in PHP.

Check it out.

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


// Example:

var employees = [
    { id: '1', sex: 'm', city: 'Paris' }, 
    { id: '2', sex: 'f', city: 'London' },
    { id: '3', sex: 'f', city: 'New York' },
    { id: '4', sex: 'm', city: 'Moscow' },
    { id: '5', sex: 'm', city: 'Berlin' }
]


// Open dev console (F12) to see results:

console.log(dump(employees));

查看更多
狗以群分
7楼-- · 2019-01-08 03:41

Firebug.

Then, in your javascript:

var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);

Now you can look at the console, click on the statement and see what is inside blah

查看更多
登录 后发表回答