문제

JavaScript 객체의 내용을 우리와 같은 문자열 형식으로 표시하는 방법 alert 변수?

객체를 표시하고 싶은 동일한 형식의 방식입니다.

도움이 되었습니까?

해결책

디버깅 목적으로 객체를 인쇄하려면 코드를 사용하십시오.

var obj = {prop1: 'prop1Value', prop2: 'prop2Value', child: {childProp1: 'childProp1Value'}}
console.log(obj)

표시됩니다 :

screenshot console chrome

메모: 당신은해야합니다 객체를 기록하십시오. 예를 들어, 이것은 작동하지 않습니다.

console.log('My object : ' + obj)

다른 팁

네이티브를 사용하십시오 JSON.stringify 방법. 중첩 된 물체 및 모든 주요 브라우저와 함께 작동합니다 지원하다 이 방법.

str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()

다음으로 연결 모질라 API 참조 그리고 다른 예.

obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)

관습을 사용하십시오 JSON.Stringify 교체기 이 JavaScript 오류가 발생하면

"Uncaught TypeError: Converting circular structure to JSON"
var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);

console.dir(object):

지정된 JavaScript 객체의 속성에 대한 대화식 목록을 표시합니다. 이 목록을 사용하면 공개 삼각형을 사용하여 자식 물체의 내용을 검사 할 수 있습니다.

주목하십시오 console.dir() 기능은 비표준입니다. 보다 MDN 웹 문서

이 시도 :

console.log(JSON.stringify(obj))

이것은 객체의 Stringify 버전을 인쇄합니다. 그래서 대신 [object] 출력으로 객체의 내용을 얻을 수 있습니다.

Firefox (세부 정보에 대한 @Bojangles 덕분에) Object.toSource() 객체를 JSON으로 인쇄하는 방법 function(){}.

그것은 대부분의 디버깅 목적으로 충분하다고 생각합니다.

경고를 사용하려면 객체를 인쇄하려면 다음을 수행 할 수 있습니다.

alert("myObject is " + myObject.toSource());

각 속성과 해당 값을 문자열 형식으로 인쇄해야합니다.

nodejs에서는 사용하여 객체를 인쇄 할 수 있습니다 util.inspect(obj). 깊이를 명시하십시오. 그렇지 않으면 물체의 얕은 인쇄 만 있으면됩니다.

표 형식으로 데이터를 보려면 사용할 수 있습니다.

console.table(obj);

테이블 열을 클릭하면 테이블을 정렬 할 수 있습니다.

표시 할 열을 선택할 수도 있습니다.

console.table(obj, ['firstName', 'lastName']);

Console.table에 대한 자세한 정보를 찾을 수 있습니다 여기

기능:

var print = function(o){
    var str='';

    for(var p in o){
        if(typeof o[p] == 'string'){
            str+= p + ': ' + o[p]+'; </br>';
        }else{
            str+= p + ': { </br>' + print(o[p]) + '}';
        }
    }

    return str;
}

용법:

var myObject = {
    name: 'Wilson Page',
    contact: {
        email: 'wilson@hotmail.com',
        tel: '123456789'
    }  
}

$('body').append( print(myObject) );

예시:

http://jsfiddle.net/wilsonpage/6eqmn/

내가 가장 앞서서 내가 찾은 가장 간단한 방법은

var getPrintObject=function(object)
{
    return JSON.stringify(object);
}

이것을 사용하십시오 :

console.log('print object: ' + JSON.stringify(session));

전체 객체를 인쇄하려면 node.js 보너스로 색상으로 :

console.dir(object, {depth: null, colors: true})

색상은 물론 선택 사항입니다. '깊이 : NULL'은 전체 객체를 인쇄합니다.

옵션은 브라우저에서 지원되지 않는 것 같습니다.

참조 :

https://developer.mozilla.org/en-us/docs/web/api/console/dir

https://nodejs.org/api/console.html#console_console_dir_obj_options

전체 길이의 객체를 인쇄하려면 사용할 수 있습니다.

console.log (require ( 'util'). 검사 (obj, {showhidden : false, depth : null})

객체를 문자열로 변환하여 인쇄하려면

console.log (json.stringify (obj));

(이것은 내 도서관에 추가되었습니다 github)

여기 바퀴를 재창조! 이 솔루션 중 어느 것도 내 상황에서 효과가 없었습니다. 그래서 나는 PageWil의 답변을 신속하게 다루었습니다. 이것은 스크린으로 인쇄하는 것이 아닙니다 (콘솔, 텍스트 필드 등). 그러나 데이터 전송을위한 것입니다. 이 버전은 매우 유사한 결과를 반환하는 것 같습니다. toSource(). 나는 시도하지 않았다 JSON.stringify, 그러나 나는 이것이 거의 같은 것이라고 생각합니다. 이 기능의 결과는 유효한 JavaScript 객체 선언입니다.

나는 이와 같은 것이 이미 어딘가에 있는지 의심 할 여지가 없지만 과거의 답변을 검색하는 데 시간을 보내는 것보다 더 짧았습니다. 그리고이 질문은 내가 이것에 대해 검색하기 시작했을 때 Google의 최고 히트 였기 때문에; 나는 여기에 그것을 넣는 것이 다른 사람들에게 도움이 될 것이라고 생각했습니다.

어쨌든,이 함수의 결과는 객체가 객체와 배열에 포함 된 경우에도 해당 객체 또는 배열이 더 내장 된 객체 및 배열을 갖는 경우에도 객체의 문자열 표현이됩니다. (나는 당신이 마시는 것을 좋아한다고 들었습니까? 그래서 나는 차가운데 차를 닦았다. 그리고 나는 더 시원하게 당신의 쿨러를 닦았다.

배열은 함께 저장됩니다 [] 대신에 {} 따라서 키/값 쌍이 있지 않고 값 만 있습니다. 일반 배열처럼. 따라서 배열처럼 만들어집니다.

또한 모든 문자열 (키 이름 포함)이 인용되며,이 문자열에 특수 문자 (공간이나 슬래시와 같은)가 없으면 필요하지 않습니다. 그러나, 나는 여전히 잘 작동하는 인용문을 제거하기 위해 이것을 감지하고 싶지 않았습니다.

그런 다음이 결과 문자열을 사용할 수 있습니다 eval 또는 문자열 조작을 통해 var에 덤프하십시오. 따라서 텍스트에서 객체를 다시 생성하십시오.

function ObjToSource(o){
    if (!o) return 'null';
    var k="",na=typeof(o.length)=="undefined"?1:0,str="";
    for(var p in o){
        if (na) k = "'"+p+ "':";
        if (typeof o[p] == "string") str += k + "'" + o[p]+"',";
        else if (typeof o[p] == "object") str += k + ObjToSource(o[p])+",";
        else str += k + o[p] + ",";
    }
    if (na) return "{"+str.slice(0,-1)+"}";
    else return "["+str.slice(0,-1)+"]";
}

내가 모든 것을 엉망으로 만들면 테스트에서 잘 작동하는지 알려주세요. 또한 유형을 감지 할 수있는 유일한 방법 array 의 존재를 확인하는 것이 었습니다 length. JavaScript는 실제로 배열을 객체로 저장하기 때문에 실제로 유형을 확인할 수 없습니다. array (그런 유형은 없습니다!). 다른 사람이 더 나은 방법을 알고 있다면 듣고 싶습니다. 객체에도 이름이 지정된 속성이있는 경우 length 이 기능은 실수로 배열로 취급됩니다.

편집 : NULL 값 객체에 대한 점검을 추가했습니다. 감사합니다 Brock Adams

편집 : 아래는 무한히 재귀 객체를 인쇄 할 수있는 고정 된 기능입니다. 이것은 동일하게 인쇄되지 않습니다 toSource FF에서 toSource 무한 재귀를 한 번 인쇄합니다.이 기능은 즉시 죽일 것입니다. 이 기능은 위의 기능보다 느리게 실행되므로 위의 기능을 편집하는 대신 여기에 추가하고 있습니다.

const ObjToSource=(o)=> {
    if (!o) return null;
    let str="",na=0,k,p;
    if (typeof(o) == "object") {
        if (!ObjToSource.check) ObjToSource.check = new Array();
        for (k=ObjToSource.check.length;na<k;na++) if (ObjToSource.check[na]==o) return '{}';
        ObjToSource.check.push(o);
    }
    k="",na=typeof(o.length)=="undefined"?1:0;
    for(p in o){
        if (na) k = "'"+p+"':";
        if (typeof o[p] == "string") str += k+"'"+o[p]+"',";
        else if (typeof o[p] == "object") str += k+ObjToSource(o[p])+",";
        else str += k+o[p]+",";
    }
    if (typeof(o) == "object") ObjToSource.check.pop();
    if (na) return "{"+str.slice(0,-1)+"}";
    else return "["+str.slice(0,-1)+"]";
}

테스트:

var test1 = new Object();
test1.foo = 1;
test1.bar = 2;

var testobject = new Object();
testobject.run = 1;
testobject.fast = null;
testobject.loop = testobject;
testobject.dup = test1;

console.log(ObjToSource(testobject));
console.log(testobject.toSource());

결과:

{'run':1,'fast':null,'loop':{},'dup':{'foo':1,'bar':2}}
({run:1, fast:null, loop:{run:1, fast:null, loop:{}, dup:{foo:1, bar:2}}, dup:{foo:1, bar:2}})

참고 : 인쇄하려고합니다 document.body 끔찍한 예입니다. 우선, FF는 사용시 빈 개체 문자열을 인쇄합니다. toSource. 위의 기능을 사용할 때 FF가 충돌합니다. SecurityError: The operation is insecure.. 그리고 크롬은 충돌합니다 Uncaught RangeError: Maximum call stack size exceeded. 분명히, document.body 문자열로 변환되지 않았습니다. 특정 속성에 액세스하기에는 너무 크거나 보안 정책에 반대하기 때문입니다. 그렇지 않으면, 나는 여기서 무언가를 엉망으로 만들었습니다.

PageWil의 답변이 제공 한 객체를 재귀 적으로 인쇄하는 방법이 필요했습니다 (감사합니다!). 나는 특정 수준까지 인쇄하는 방법을 포함시키고 간격을 추가하여 우리가있는 현재 레벨을 기준으로 적절히 들여 쓰기를 추가하여 더 읽을 수 있도록 약간 업데이트했습니다.

// Recursive print of object
var print = function( o, maxLevel, level ) {
    if ( typeof level == "undefined" ) {
        level = 0;
    }
    if ( typeof level == "undefined" ) {
        maxLevel = 0;
    }

    var str = '';
    // Remove this if you don't want the pre tag, but make sure to remove
    // the close pre tag on the bottom as well
    if ( level == 0 ) {
        str = '<pre>';
    }

    var levelStr = '';
    for ( var x = 0; x < level; x++ ) {
        levelStr += '    ';
    }

    if ( maxLevel != 0 && level >= maxLevel ) {
        str += levelStr + '...</br>';
        return str;
    }

    for ( var p in o ) {
        if ( typeof o[p] == 'string' ) {
            str += levelStr +
                p + ': ' + o[p] + ' </br>';
        } else {
            str += levelStr +
                p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}</br>';
        }
    }

    // Remove this if you don't want the pre tag, but make sure to remove
    // the open pre tag on the top as well
    if ( level == 0 ) {
        str += '</pre>';
    }
    return str;
};

용법:

var pagewilsObject = {
    name: 'Wilson Page',
    contact: {
        email: 'wilson@hotmail.com',
        tel: '123456789'
    }  
}

// Recursive of whole object
$('body').append( print(pagewilsObject) ); 

// Recursive of myObject up to 1 level, will only show name 
// and that there is a contact object
$('body').append( print(pagewilsObject, 1) ); 

간단히 사용하십시오

JSON.stringify(obj)

예시

var args_string = JSON.stringify(obj);
console.log(args_string);

또는

alert(args_string);

또한 JavaScript 함수에서 참고는 객체로 간주됩니다.

실제로 당신은 이와 같은 새로운 속성을 할당 할 수 있습니다

foo.moo = "stackoverflow";
console.log(foo.moo);

NB :이 예에서 YourOBJ는 검사하려는 객체를 정의합니다.

먼저 내가 가장 좋아하지만 가장 활용된 객체를 표시하는 방법 :

이것은 객체의 내용을 보여주는 defacto 방법입니다.

console.log(yourObj)

다음과 같은 것을 생산합니다.enter image description here

최상의 솔루션은 객체 키를 살펴보고 객체가 무엇을 보유하고 있는지 정말로보고 싶다면 객체 값을 통해 ...

console.log(Object.keys(yourObj));
console.log(Object.values(yourObj));

다음과 같은 것을 출력합니다.enter image description here(위의 그림 : 객체에 저장된 키/값)

ECMAScript 2016 또는 최신을 사용하는 경우이 새로운 옵션도 있습니다.

Object.keys(yourObj).forEach(e => console.log(`key=${e}  value=${yourObj[e]}`));

이것은 깔끔한 출력을 생성합니다.enter image description here이전 답변에서 언급 된 솔루션 : console.log(yourObj) 너무 많은 매개 변수를 표시합니다 원하는 데이터를 표시하는 가장 사용자 친화적 인 방법이 아닙니다.. 그렇기 때문에 키를 로깅 한 다음 별도로 값을 추천합니다.

다음 :

console.table(yourObj)

이전 의견에있는 누군가가 이것을 제안했지만 결코 저에게 효과가 없었습니다. 다른 브라우저 나 다른 사람에게 효과가 있다면 Kudos! 참조를 위해 여전히 코드를 여기에 넣을 것입니다! 이와 같은 것을 콘솔에 출력합니다.enter image description here

다음은 다음과 같은 방법입니다.

console.log("%o", obj);

가장 간단한 방법 :

console.log(obj);

또는 메시지와 함께 :

console.log("object is: %O", obj);

전달한 첫 번째 객체에는 하나 이상의 형식 지정자가 포함될 수 있습니다. 형식 지정자는 백분율 부호 (%)와 적용 할 형식을 나타내는 문자로 구성됩니다.

더 많은 형식 지정자

나는 항상 사용합니다 console.log("object will be: ", obj, obj1). 이렇게하면 JSON과 함께 Stringify와 함께 해결 방법을 할 필요가 없습니다. 객체의 모든 속성은 멋지게 확장됩니다.

콘솔 내에 객체를 표시하는 또 다른 방법은 다음과 같습니다. JSON.stringify. 아래 예를 확인하십시오.

var gandalf = {
  "real name": "Gandalf",
  "age (est)": 11000,
  "race": "Maia",
  "haveRetirementPlan": true,
  "aliases": [
    "Greyhame",
    "Stormcrow",
    "Mithrandir",
    "Gandalf the Grey",
    "Gandalf the White"
  ]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));
var list = function(object) {
   for(var key in object) {
     console.log(key);
   }
}

어디 object 당신의 대상입니다

또는 Chrome Dev 도구 인 "Console"탭에서 이것을 사용할 수 있습니다.

console.log(object);

물체를 가정합니다 obj = {0:'John', 1:'Foo', 2:'Bar'}

객체의 내용을 인쇄하십시오

for (var i in obj){
    console.log(obj[i], i);
}

콘솔 출력 (Chrome Devtools) :

John 0
Foo 1
Bar 2

도움이되기를 바랍니다!

자바 스크립트 기능

<script type="text/javascript">
    function print_r(theObj){ 
       if(theObj.constructor == Array || theObj.constructor == Object){ 
          document.write("<ul>") 
          for(var p in theObj){ 
             if(theObj[p].constructor == Array || theObj[p].constructor == Object){ 
                document.write("<li>["+p+"] => "+typeof(theObj)+"</li>"); 
                document.write("<ul>") 
                print_r(theObj[p]); 
                document.write("</ul>") 
             } else { 
                document.write("<li>["+p+"] => "+theObj[p]+"</li>"); 
             } 
          } 
          document.write("</ul>") 
       } 
    } 
</script>

인쇄 대상

<script type="text/javascript">
print_r(JAVACRIPT_ARRAY_OR_OBJECT);
</script> 

~을 통해 JavaScript의 print_r

작은 도우미 기능은 콘솔을 통해 간단하고 빠른 디버깅을 위해 프로젝트에서 항상 사용합니다. Laravel에서 가져온 영감.

/**
 * @param variable mixed  The var to log to the console
 * @param varName string  Optional, will appear as a label before the var
 */
function dd(variable, varName) {
    var varNameOutput;

    varName = varName || '';
    varNameOutput = varName ? varName + ':' : '';

    console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
}

용법

dd(123.55); 출력 :
enter image description here

var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj'); 

enter image description here

나는 사용하는 것을 선호한다 console.table 명확한 개체 형식을 얻으려면이 개체가 있다고 상상해보십시오.

const obj = {name: 'Alireza', family: 'Dezfoolian', gender: 'male', netWorth: "$0"};

그리고 당신은 다음과 같은 깔끔하고 읽을 수있는 테이블을 볼 것입니다.console.table

PageWil의 인쇄 방법을 사용했는데 매우 잘 작동했습니다.

다음은 (슬로피) 들여 쓰기와 뚜렷한 소품/OB 구분기가있는 약간 확장 된 버전입니다.

var print = function(obj, delp, delo, ind){
    delp = delp!=null ? delp : "\t"; // property delimeter
    delo = delo!=null ? delo : "\n"; // object delimeter
    ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
    var str='';

    for(var prop in obj){
        if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
          var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
          str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
        }else{
          str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
        }
    }
    return str;
};

PageWils 코드의 또 다른 수정 ... 그의 문자열 이외의 다른 것을 인쇄하지 않고 숫자와 부울 필드를 비워두고 Megaboss가 만든 기능 내부의 두 번째 유형에서 오타를 고정했습니다.

var print = function( o, maxLevel, level )
{
    if ( typeof level == "undefined" )
    {
        level = 0;
    }
    if ( typeof maxlevel == "undefined" )
    {
        maxLevel = 0;
    }

    var str = '';
    // Remove this if you don't want the pre tag, but make sure to remove
    // the close pre tag on the bottom as well
    if ( level == 0 )
    {
        str = '<pre>';   // can also be <pre>
    }

    var levelStr = '<br>';
    for ( var x = 0; x < level; x++ )
    {
        levelStr += '    ';   // all those spaces only work with <pre>
    }

    if ( maxLevel != 0 && level >= maxLevel )
    {
        str += levelStr + '...<br>';
        return str;
    }

    for ( var p in o )
    {
        switch(typeof o[p])
        {
          case 'string':
          case 'number':    // .tostring() gets automatically applied
          case 'boolean':   // ditto
            str += levelStr + p + ': ' + o[p] + ' <br>';
            break;

          case 'object':    // this is where we become recursive
          default:
            str += levelStr + p + ': [ <br>' + print( o[p], maxLevel, level + 1 ) + levelStr + ']</br>';
            break;
        }
    }

    // Remove this if you don't want the pre tag, but make sure to remove
    // the open pre tag on the top as well
    if ( level == 0 )
    {
        str += '</pre>';   // also can be </pre>
    }
    return str;
};

여기 기능이 있습니다.

function printObj(obj) {
console.log((function traverse(tab, obj) {
    let str = "";
    if(typeof obj !== 'object') {
        return obj + ',';
    }
    if(Array.isArray(obj)) {            
        return '[' + obj.map(o=>JSON.stringify(o)).join(',') + ']' + ',';
    }
    str = str + '{\n';
    for(var p in obj) {
        str = str + tab + ' ' + p + ' : ' + traverse(tab+' ', obj[p]) +'\n';
    }
    str = str.slice(0,-2) + str.slice(-1);                
    str = str + tab + '},';
    return str;
}('',obj).slice(0,-1)))};

가독성이있는 탭 계집을 사용하여 객체를 표시 할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top