使用javascript遍历对象的属性和方法
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="lib/jquery-1.8.2.js"></script> <script type="text/javascript"> //对象 function Programmer() { this.name = "李小牛"; this.sex = "男"; this.age = 25; this.work = proFun; } //方法 function proFun() { $("#function").append("程序员的工作是写代码"); } function foreachObj() { //声明对象 var pro = new Programmer(); //遍历对象属性 for (var p in pro) { //判断是否为方法 if (typeof (pro[p]) == "function") { //执行放阿飞 pro[p](); } else { //打印属性 $("#attribute").append(p + ":" + pro[p] + "\t"); } } } </script> </head> <body> <input type="button" value="执行对象方法" onclick="foreachObj()" /> <div id="attribute"></div> <div id="function"></div> </body> </html>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步