How can I view an object with an alert() [duplicate] - javascript

This question already has answers here:
How can I display a JavaScript object?
(40 answers)
Closed 2 months ago.
I tried to do a debug but I am having problems. Now I try with alert(). For example I want to see the value of:
var product = { ProductName: $('!Answer_Response[0]').val(),
UnitPrice: $('#Price').val(),
Stock: $('#Stock').val()
};
When I say alert(product) it just gives me [object Object]. How can I make alert show what's really there?

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

You should really use Firebug or Webkit's console for debugging. Then you can just do console.debug(product); and examine the object.

Try this:
alert(JSON.parse(product) );

Use Javascript native JSON.stringify method. To visualise it in a nicer way, you can use, like: JSON.stringify(obj,null, 4)
var obj = {data:[{"empmenuid":"1","empid":null,"deptid":"66","aliasid":"66","firstname":"66","lastname":"66","sin":"66","status":"66","empclass":"66","hiredate":"66","seneoritydate":"66","separationdate":"66"},{"empmenuid":"3","empid":null,"deptid":"12","aliasid":"12","firstname":"12","lastname":"12","sin":"12","status":"12","empclass":"12","hiredate":"12","seneoritydate":"12","separationdate":"12","recalldate":"12","martialstatus":"12","gender":"12","pager":"12","locid":"12","jobtitle":"12","jobtitlestart":"12","fullpart":"12","manager":"12","managername":"12","middlename":"12","nickname":"12","paytype":"12","payfreq":"12"}],
recordType : 'object'};
alert(JSON.stringify(obj,null, 4));

Depending on which property you are interested in:
alert(product.ProductName);
alert(product.UnitPrice);
alert(product.Stock);

alert( JSON.stringify(product) );

alert (product.UnitName + " " + product.UnitPrice + " " + product.Stock)
or else create a toString() method on your object and call
alert(product.toString())
But I have to agree with other posters - if it is debugging you're going for then firebug or F12 on IE9 or chrome and using console.log is the way to go

Related

Screeps: write debug output to console?

Is there a way of getting screeps code to print strings to the console (or anywhere really) for simple debugging purposes?
You can use standard console.log method for that.
I use the following to print objects to the console:
console.log(JSON.stringify(<myVariable>))
I can't find how to do this in Docs. Had to write something like this:
module.exports = function () {
var log = Memory.log;
if(log === null || log === undefined){
log = Memory.log = [];
}
var parts = ["["+Game.time+"]"];
for(var i in arguments){
parts.push(arguments[i]);
}
var msg = parts.join(" ");
log.push(msg);
if(log.length > 10){
log.shift();
}
}
Will be grateful if someone can provide a better solution.
Sometimes when you do console.log you get unhelpful string representations of objects, something like like "[Object]".
If you want to drill down into the object and check out it's properties, the easiest solution is to open your browser's console. The devs made it so any console.log in your script will also reach the standard browser console. I believe it works in all major browsers.

Each for object? [duplicate]

This question already has answers here:
Iterate over Object Literal Values
(8 answers)
Closed 3 years ago.
I have object in JavaScript:
var object = someobject;
Object { aaa=true, bbb=true, ccc=true }
How can I use each for this?
object.each(function(index, value)) {
console.log(value);
}
Not working.
A javascript Object does not have a standard .each function. jQuery provides a function. See http://api.jquery.com/jQuery.each/ The below should work
$.each(object, function(index, value) {
console.log(value);
});
Another option would be to use vanilla Javascript using the Object.keys() and the Array .map() functions like this
Object.keys(object).map(function(objectKey, index) {
var value = object[objectKey];
console.log(value);
});
See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/keys and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
These are usually better than using a vanilla Javascript for-loop, unless you really understand the implications of using a normal for-loop and see use for it's specific characteristics like looping over the property chain.
But usually, a for-loop doesn't work better than jQuery or Object.keys().map(). I'll go into two potential issues with using a plain for-loop below.
Right, so also pointed out in other answers, a plain Javascript alternative would be
for(var index in object) {
var attr = object[index];
}
There are two potential issues with this:
1 . You want to check whether the attribute that you are finding is from the object itself and not from up the prototype chain. This can be checked with the hasOwnProperty function like so
for(var index in object) {
if (object.hasOwnProperty(index)) {
var attr = object[index];
}
}
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty for more information.
The jQuery.each and Object.keys functions take care of this automatically.
2 . Another potential issue with a plain for-loop is that of scope and non-closures. This is a bit complicated, but take for example the following code. We have a bunch of buttons with ids button0, button1, button2 etc, and we want to set an onclick on them and do a console.log like this:
<button id='button0'>click</button>
<button id='button1'>click</button>
<button id='button2'>click</button>
var messagesByButtonId = {"button0" : "clicked first!", "button1" : "clicked middle!", "button2" : "clicked last!"];
for(var buttonId in messagesByButtonId ) {
if (messagesByButtonId.hasOwnProperty(buttonId)) {
$('#'+buttonId).click(function() {
var message = messagesByButtonId[buttonId];
console.log(message);
});
}
}
If, after some time, we click any of the buttons we will always get "clicked last!" in the console, and never "clicked first!" or "clicked middle!". Why? Because at the time that the onclick function is executed, it will display messagesByButtonId[buttonId] using the buttonId variable at that moment. And since the loop has finished at that moment, the buttonId variable will still be "button2" (the value it had during the last loop iteration), and so messagesByButtonId[buttonId] will be messagesByButtonId["button2"], i.e. "clicked last!".
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures for more information on closures. Especially the last part of that page that covers our example.
Again, jQuery.each and Object.keys().map() solve this problem automatically for us, because it provides us with a function(index, value) (that has closure) so we are safe to use both index and value and rest assured that they have the value that we expect.
for(var key in object) {
console.log(object[key]);
}
var object = { "a": 1, "b": 2};
$.each(object, function(key, value){
console.log(key + ": " + object[key]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
//output
a: 1
b: 2

jQuery append fail in IE

I have this object that I would like to append to my div#doctors-list.
Firefox,Chrome work like a charm.But all IE fail. No errors are shown in the console.
$.each(sorteddoctorsArray[i2], function(idx, val) {
if ( !$.browser.msie ) {
$('div#doctors-list').append(val);
}else{
console.log(val);
// this logs [object Object]
$('div#doctors-list').append(val); // fails
}
});
any suggestions?
open it in IE and firefox to see the difference
try:
$('div#doctors-list').html($('div#doctors-list').html()+val);
It's hard to say when you disable the IE-Code(it currently is commented out).
But one issue I see so far(a few lines above the code posted by you) :
$('div#doctors-list').html('');
for(var i in priority){
for(var i2 in sorteddoctorsArray){
Both, priority and sorteddoctorsArray are native Arrays, you should never walk native Arrays by using for...in, always use for(var i=0;i<array.length;++i)
The for...in -Syntax will walk trough all members of an object. Also the build-in Array-members, e.g. length , will be fetched, what may result in errors.

results.shift is not a function: firefox extension

I've written this code in Firefox JS extension
var results = gBrowser.contentDocument.getElementsByClassName("b-serp-item__title-link");
alert(results.length);
var countToDelete = results.length - 10;
alert(countToDelete);
if (countToDelete > 0)
{
for (var i = 0; i < countToDelete; i++);
{
alert("I prepare");
results.shift();
alert("I done");
}
}
alert("succ");
And I've got this output
results.length=12
countToDelete=2
(I prepare)
and... that's all
There is a problem at results.shift();
I looked in Firefox Error Console and I found this
"results.shift is not a function"
Why? Is shift a js function?
When I try to run this code in firefox console I've got this error again
What's the matter?
My version of Firefox is 4.
Tested url is http://yandex.ru/yandsearch?text=%D0%BE%D0%B1%D0%BE%D0%B9%D0%BD%D1%8B%D0%B9+%D0%BA%D0%BB%D0%B5%D0%B9+%D0%BA%D1%83%D0%BF%D0%B8%D1%82%D1%8C&lr=37
this will convert your nodelist to a real Array, which has a usable shift method:
var results = Array.prototype.slice.call(
gBrowser
.contentDocument
.getElementsByClassName("b-serp-item__title-link")
);
I think it's clear that there is no such thing as shift() in Gecko:
https://developer.mozilla.org/En/DOM/NodeList
The main question is what you want to achieve by it? By removing items form the NodeList you are certainly not removing them from the DOM document. What is your quarrel with removeChild()?
You need to convert the HTMLCollection to an array if you want to use shift() :
Most efficient way to convert an HTMLCollection to an Array

How to check null objects in jQuery

I'm using jQuery and I want to check the existence of an element in my page. I have written following code, but it's not working:
if($("#btext" + i) != null) {
//alert($("#btext" + i).text());
$("#btext" + i).text("Branch " + i);
}
How do I check the existence of the element?
Check the jQuery FAQ...
You can use the length property of the jQuery collection returned by your selector:
if ( $('#myDiv').length ){}
(Since I don't seem to have enough reputation to vote down the answer...)
Wolf wrote:
Calling length property on undefined
or a null object will cause IE and
webkit browsers to fail!
Instead try this:
// NOTE!! THE FOLLOWING IS WRONG; DO NOT USE! -- EleotleCram
if($("#something") !== null){
// do something
}
or
// NOTE!! THE FOLLOWING IS WRONG; DO NOT USE! -- EleotleCram
if($("#something") === null){
// don't do something
}
While it is true that calling the length property on an undefined or null object will cause browsers to fail, the result of jQuery's selectors (the $('...')) will never be null or undefined. Thus the code suggestions make no sense. Use one of the other answers, they make more sense.
(Update 2012) Because people look at code and this answer is pretty high up the list: For the last couple of years, I have been using this small plugin:
jQuery.fn['any'] = function() {
return (this.length > 0);
};
I think $('div').any() reads better than $('div').length, plus you won't suffer as much from typos: $('div').ayn() will give a runtime error, $('div').lenght will silently most likely always be falsy.
__
Edits november 2012:
1) Because people tend to look at code and not read what is said around the code, I added two big caveat lector notes to the quoted code of Wolf.
2) I added code of the small plugin I use for this situation.
The lookup function returns an array of matching elements. You could check if the length is zero. Note the change to only look up the elements once and reuse the results as needed.
var elem = $("#btext" + i);
if (elem.length != 0) {
elem.text("Branch " + i);
}
Also, have you tried just using the text function -- if no element exists, it will do nothing.
$("#btext" + i).text("Branch " + i);
jquery $() function always return non null value - mean elements matched you selector cretaria. If the element was not found it will return an empty array.
So your code will look something like this -
if ($("#btext" + i).length){
//alert($("#btext" + i).text());
$("#btext" + i).text("Branch " + i);
}
In jQuery 1.4 you get the $.isEmptyObject function, but if you are forced to use an older version of jQ like us poor Drupal developers just steal use this code:
// This is a function similar to the jQuery 1.4 $.isEmptyObject.
function isObjectEmpty(obj) {
for ( var name in obj ) {
return false;
}
return true;
}
Use it like:
console.log(isObjectEmpty(the_object)); // Returns true or false.
What about using "undefined"?
if (value != undefined){ // do stuff }
no matter what you selection is the function $() always returns a jQuery object so that cant be used to test. The best way yet (if not the only) is to use the size() function or the native length property as explained above.
if ( $('selector').size() ) {...}
if ( $('#whatever')[0] ) {...}
The jQuery object which is returned by all native jQuery methods is NOT an array, it is an object with many properties; one of them being a "length" property. You can also check for size() or get(0) or get() - 'get(0)' works the same as accessing the first element, i.e. $(elem)[0]
use $("#selector").get(0) to check with null like that. get returns the dom element, until then you re dealing with an array, where you need to check the length property. I personally don't like length check for null handling, it confuses me for some reason :)
Using the length property you can do this.
jQuery.fn.exists = function(){return ($(this).length < 0);}
if ($(selector).exists()) {
//do somthing
}
when the object is empty return this error:
Uncaught TypeError: Cannot read property '0' of null
I try this code :
try{
if ($("#btext" + i).length) {};
}catch(err){
if ($("#btext" + i).length) {
//working this code if the item, not NULL
}
}
if (typeof($("#btext" + i)) == 'object'){
$("#btext" + i).text("Branch " + i);
}
Calling length property on undefined or a null object will cause IE and webkit browsers to fail!
Instead try this:
if($("#something") !== null){
// do something
}
or
if($("#something") === null){
// don't do something
}

Categories

Resources