Jump to content

spence911
Go to solution Solved by .josh,

Recommended Posts

I would really appreciate some assistance on how I can print out the values of object1, object2 and object3 from the code down below. Using document.write(object1); for example prints out [object Object] instead of the actual values.

<script type="text/javascript">

var object1 = {value: 10};
var object2 = object1;
var object3 = {value: 10};

</script>

If it helps my browser is Google chrome.Thanks.

Link to comment
Share on other sites

you could use console.log and the object is written in the console (for example firebug in firefox). 
if you really need to write the values in the document you could use this:
 

/* 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
  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, recursionLevel) {
    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], 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], recursionLevel + 1) + "\n";
                    cnt++;
                }
                sContents += repeatString('   ', recursionLevel) + "}";
                out += "(" + cnt + "): " + sContents;
            }
            break;
    }
    var pre = document.createElement('pre');
    pre.innerHTML = out;
    document.body.appendChild(pre)

    return out;
} 

(edited version of http://stackoverflow.com/a/11315561)

 

Then you can use it with just 

dump(yourVariable)
Link to comment
Share on other sites

  • Solution

You might wanna be more specific about what you're trying to actually do. Generally you shouldn't really use document.write for anything. If you are just playing around with stuff, you should use console.log() instead. Chrome has a built-in set of developer tools. Go to the menu and Tools > Developer Tools, (shortcut Ctrl+Shift+I). You can go to the "Console" tab to type in javascript code or see the results of calls to console.log().

 

If you are attempting to print (output) the code somewhere else, like visibly on your page, then you should be using methods to change an html element's value or text, or create one, etc.. There are numerous ways to do this, so more specific advice can come with more specific description of what you are actually trying to do.

 

But as for a "dump" of what a javascript object contains, you can reference individual properties with dot notation or index notation

 

var object1 = {value: 10};
console.log(object1.value); // dot notation
console.log(object1['value']); // index notation
You can also loop through the properties with the in loop:

 

var object1 = {value: 10, foo:'bar'};
for (x in object1) {
  // x will have the name of the property, so we can get the value of each property 
  // by using index notation
  console.log(object1[x]);
}
But as far as (recursively) outputting a "tree" of everything in the object (e.g. the equivalent of php's var_dump or print_r), javascript has no native method for this (for some odd reason). I have not tested to see if the code phpzer works as advertised, but you will basically need to something like that. If you google for "javascript equivalent of var_dump" you will find plenty of example functions people have made to replicate it.

 

Though honestly, there isn't much use case for something like this, other than for qa/debug purposes, and if that's what you are looking to do, then the javascript/dev console already offers a really nicely formatted way to visualize an object. For example, if you go to the Chrome dev console and type in

 

var object1 = {value: 10, foo:'bar'};
And then type on "object1"

 

It will output the following:

 

Object {value: 10, foo: "bar"}
If the object is more complex, it will output it in a way that has little arrows you can click on to expand it to a tree view. For example, you can type "document" into the console and get an expandable tree-view of what the rendered document looks like. It's basically like right-click > viewsource but with the fully rendered content (fyi if you want to utilize that, go to the "Elements" tab of the dev console instead, since that's what it's all about). Or, type in "window" to see the window object. From there you can drill down and find any variable set (since window is the highest scope for js)
Link to comment
Share on other sites

  • 2 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.