What is the JavaScript Equivalent of PHP print_r() function? In other words, how you can “print” a javascript object in a way that’s readable by humans?
Code
You could use JSON.stringify, as following:
The HTML part
Let’s create two links for demo:
<p><a id="print_demo" href="javascript:void(0);">Print object</a></p>
<p><a id="pretty_print_demo" href="javascript:void(0);">Pretty Print object</a>
The JAVASCRIPT part
Remark: I use jQuery to handle events, but you can use plain javascript (if you prefer).
<script type="text/javascript">
$(function() {
// create an object
var person = new Object();
person.firstname = "John";
person.lastname = "Doe";
person.age = "35";
// plain print
$("#print_demo").click(function() {
alert(JSON.stringify(person));
});
// pretty print
$("#pretty_print_demo").click(function() {
alert(JSON.stringify(person, null, ' '));
});
});
</script>