如何检查Javascript对象

如何检查警报框中的对象? 通常提醒一个对象只是抛出nodename:

alert(document); 

但是我想要在警告框中获取对象的属性和方法。 如果可能,我怎样才能实现这个function? 或者还有其他build议吗?

特别是,我正在寻找一个生产环境的console.log和Firebug不可用的解决scheme。

对象或数组中每个属性的forin循环。 您可以使用此属性来获取值并更改它。

注:除非您使用“间谍”,否则私人财产不可用于检查。 基本上,你重写对象,并编写一些代码,在对象的上下文中执行for-in循环。

因为看起来像:

 for (var property in object) loop(); 

一些示例代码:

 function xinspect(o,i){ if(typeof i=='undefined')i=''; if(i.length>50)return '[MAX ITERATIONS]'; var r=[]; for(var p in o){ var t=typeof o[p]; r.push(i+'"'+p+'" ('+t+') => '+(t=='object' ? 'object:'+xinspect(o[p],i+' ') : o[p]+'')); } return r.join(i+'\n'); } // example of use: alert(xinspect(document)); 

编辑:前一段时间,我写了我自己的督察,如果你有兴趣,我很乐意分享。

编辑2:好吧,我写了一个。

如何通过现代浏览器alert(JSON.stringify(object))

TypeError: Converting circular structure to JSON情况下TypeError: Converting circular structure to JSON ,这里有更多选项: 即使有循环引用,如何将DOM节点序列化为JSON?

文档: JSON.stringify()提供格式化或美化输出的信息。

使用console.dir(object)和Firebug插件

使用你的控制台:

 console.log(object); 

有几种方法:

  1. typeof tells you which one of the 6 javascript types is the object. 2. instanceof tells you if the object is an instance of another object. 3. List properties with for(var k in obj) 4. Object.getOwnPropertyNames( anObjectToInspect ) 5. Object.getPrototypeOf( anObject ) 6. anObject.hasOwnProperty(aProperty) 

在控制台上下文中,有时.constructor或.prototype可能是有用的:

 console.log(anObject.constructor ); console.log(anObject.prototype ) ; 
 var str = ""; for(var k in obj) if (obj.hasOwnProperty(k)) //omit this test if you want to see built-in properties str += k + " = " + obj[k] + "\n"; alert(str); 

这是基督徒出色答案的公然诋毁。 我只是让它更具可读性:

 /** * objectInspector digs through a Javascript object * to display all its properties * * @param object - a Javascript object to inspect * @param result - a string of properties with datatypes * * @return result - the concatenated description of all object properties */ function objectInspector(object, result) { if (typeof object != "object") return "Invalid object"; if (typeof result == "undefined") result = ''; if (result.length > 50) return "[RECURSION TOO DEEP. ABORTING.]"; var rows = []; for (var property in object) { var datatype = typeof object[property]; var tempDescription = result+'"'+property+'"'; tempDescription += ' ('+datatype+') => '; if (datatype == "object") tempDescription += 'object: '+objectInspector(object[property],result+' '); else tempDescription += object[property]; rows.push(tempDescription); }//Close for return rows.join(result+"\n"); }//End objectInspector 

这是我的对象检查器,更具可读性。 由于代码需要很长时间才能写下来,所以可以在http://etto-aa-js.googlecode.com/svn/trunk/inspector.js下载;

像这样使用:

 document.write(inspect(object));