Home > Web Front-end > JS Tutorial > body text

How to print object object in js_javascript skills

WBOY
Release: 2016-05-16 15:36:30
Original
1782 people have browsed it

js调试中经常会碰到输出的内容是对象而无法打印的时候,光靠alert只能打印出object标示,却不能打印出来里面的内容,甚是不方便,于是各方面整理总结了如下一个函数,能够将数组或者对象这类的结果一一打印出来,具体代码如下:

function writeObj(obj){ 
 var description = ""; 
 for(var i in obj){ 
  var property=obj[i]; 
  description+=i+" = "+property+"\n"; 
 } 
 alert(description); 
} 
Copy after login

另外当你需要将object对象转换为string字符串

有下面这个函数就好了,可以将其转化为字符串类型,然后就可以打印出来了,具体代码如下:

function obj2string(o){ 
 var r=[]; 
 if(typeof o=="string"){ 
  return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\""; 
 } 
 if(typeof o=="object"){ 
  if(!o.sort){ 
   for(var i in o){ 
    r.push(i+":"+obj2string(o[i])); 
   } 
   if(!!document.all&&!/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)){ 
    r.push("toString:"+o.toString.toString()); 
   } 
   r="{"+r.join()+"}"; 
  }else{ 
   for(var i=0;i<o.length;i++){ 
    r.push(obj2string(o[i])) 
   } 
   r="["+r.join()+"]"; 
  } 
  return r; 
 } 
 return o.toString(); 
} 
Copy after login

以上两步骤就能完成js打印object对象,希望对大家的学习有所帮助。

Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template