JSFiddle - React, Tailwind, and code Playground

by jfriend00

HTML

<dl id="results">
</dl>

CSS

dl {
    width: 350px;
}

dt {
    margin-right:10px;
    float:left;
    width:170px;
}

dd {
    margin: 1px 0;
}

dt, dd {
    padding: 5px;
    font-family: "Courier New";
    font-size: 12px;
    background-color: #4f7bd3;
    color: #fff;
}

JavaScript

Object.type = function _type( obj ) {
    
    function parseType(str) {
        if (str.indexOf("[object ") == 0) {
            var split = str.split(" ");
            if (split.length > 1) {
                // remove trailing ]
                return(split[1].slice(0, -1));
            }
        }
        return("");
    }
    
    var res = parseType(Object.prototype.toString.call(obj));

    // if type is generic, see if we can get a better name
    if (res === "Object") {
        res = parseType("" + obj);
        if (!res) {
            res = "Object";
        }
    }
    // protect against errors when comparing some objects vs. the window object
    if(typeof obj === "object" && "setInterval" in obj) {
        res = 'Window';
    }
    else if( res === 'Window' || res === 'Global' ) {
        res = 'Undefined';
    }
    else if( res.indexOf( 'HTML' ) === 0 ) { 
        res = 'Node';
    }

    return ( res );
};

function out(str1, str2) {
    var html = "<dt>" + str1 + ":</dt><dd>" + str2 + "</dd><div style='clear: both;'></div>";
    $("#results").append(html);
}

var testItems = [
    "window.localStorage", window.localStorage, 
    "window.location", window.location,
    "window.location.href", window.location.href,
    "1", 1, 
    "[]", ["[Object whatever]"],
    "{}", {"foo": "whatever"}, 
    "window", window, 
    "window.y", window.y, 
    "true", true, 
    "foo", "foo",
    "document", document,
    "document.body", document.body,
    "dl DOM element", document.getElementById("results"),
    "out()", out
];

for (var i = 0; i < testItems.length; i+=2) {
    out(testItems[i], Object.type(testItems[i+1]));
}