开发者

alert the object

I am setting an object like this

n.name = n.name.join(String.fro开发者_开发问答mCharCode(255));
n.description = n.description.join(String.fromCharCode(255));

I want to be able to alert(n); but it tells me [Object]

is there a way to alert complete object?

thanks


Javascript supports adding a toString() function to your objects. This will get called when you alert your object. For example:

n.toString = function(){
    return this.name + '\n' + this.description;
}

then alert(n); will display whatever content your function specifies.


I was asking the same kind of question as Autolycus today. I'm using jqGrid and I wanted to see what the object it created actually was. I didn't create the object and I wanted to see what it looked like. I know it's probably old school, but I still use alerts in javascript for some of my debugging (though I agree FireFox & Firebug are the way to go for most things).

I found an answer to what I was looking for here: http://javascript.internet.com/debug-guide.html, which is unbelievably old.

But I tweaked it to give me what I needed and since I think it answers Autolycus's question in a new way and I think someone else might be looking here, like me, for this someday, here it is:

obj = n;
var temp = "";
for (x in obj) {
    temp += x + ": " + obj[x] + "\n";
}
alert (temp);

I apologize in advance if answering an old question is breaking some kind of rule.

all best, ember


I like the var_dump in php, so I often use a function like this to dump variables

function var_dump(object, returnString)
{
  var returning = '';
  for(var element in object)
  {
    var elem = object[element];
    if(typeof elem == 'object')
    {
      elem = var_dump(object[element], true);
    }
    returning += element + ': ' + elem + '\n';
  }
  if(returning == '')
  {
    returning = 'Empty object';
  }
  if(returnString === true)
  {
    return returning;
  }
  alert(returning);
}


There are a couple of alternatives:

1. Use http://www.gscottolson.com/blackbirdjs/
2. Use console.log() that comes with Firebug, but requires Firefox (even if you only target only IEs, it's still wise to use Firefox and Firebug as aprt of testing of your web app development)


It depends what you mean by alerting the complete object.

You can't really just output every object as a string and have it make sense. To define how an object will display itself as a string we use the .toString(); method.

So try alert(n.toString()); and see if that will give you what you want. If the object is your own, then define the toString(); and have it return a string of the parameters and fields that you want to output.


Something like...

alert(n.name); 

...I think is what you want.

If you are trying to debug, you would be better suited to using FireFox/Firebug instead of inserting a load of alerts();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜