How can I view an object with an alert()
you can use the JSON.stringify()
method found in modern browsers and provided by json2.js.
var myObj = {"myProp":"Hello"};
alert (JSON.stringify(myObj)); // alerts {"myProp":"Hello"};
or
also check this library : http://devpro.it/JSON/files/JSON-js.html
you can use toSource method like this
alert(product.toSource());
If you want to easily view the contents of objects while debugging, install a tool like Firebug and use console.log
:
console.log(product);
If you want to view the properties of the object itself, don't alert
the object, but its properties:
alert(product.ProductName);
alert(product.UnitPrice);
// etc... (or combine them)
As said, if you really want to boost your JavaScript debugging, use Firefox with the Firebug addon. You will wonder how you ever debugged your code before.
This is what I use:
var result = [];
for (var l in someObject){
if (someObject.hasOwnProperty(l){
result.push(l+': '+someObject[l]);
}
}
alert(result.join('\n'));
If you want to show nested objects too, you could use something recursive:
function alertObject(obj){
var result = [];
function traverse(obj){
for (var l in obj){
if (obj.hasOwnProperty(l)){
if (obj[l] instanceof Object){
result.push(l+'=>[object]');
traverse(obj[l]);
} else {
result.push(l+': '+obj[l]);
}
}
}
}
traverse(obj);
return result;
}