Print content of JavaScript object? [duplicate]

2019-01-01 14:03发布

This question already has an answer here:

Typically if we just use alert(object); it will show as [object Object]. How to print all the content parameters of an object in JavaScript?

15条回答
余生无你
2楼-- · 2019-01-01 14:21

Print content of object you can use

console.log(obj_str);

you can see the result in console like below.

Object {description: "test"} 

For open console press F12 in chrome browser, you will found console tab in debug mode.

查看更多
永恒的永恒
3楼-- · 2019-01-01 14:25

This will give you very nice output with indented JSON object:

alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));

The second argument alters the contents of the string before returning it. The third argument specifies how many spaces to use as white space for readability.

查看更多
听够珍惜
4楼-- · 2019-01-01 14:26

You should consider using FireBug for JavaScript debugging. It will let you interactively inspect all of your variables, and even step through functions.

查看更多
孤独总比滥情好
5楼-- · 2019-01-01 14:27

Aside from using a debugger, you can also access all elements of an object using a foreach loop. The following printObject function should alert() your object showing all properties and respective values.

function printObject(o) {
  var out = '';
  for (var p in o) {
    out += p + ': ' + o[p] + '\n';
  }
  alert(out);
}

// now test it:
var myObject = {'something': 1, 'other thing': 2};
printObject(myObject);

Using a DOM inspection tool is preferable because it allows you to dig under the properties that are objects themselves. Firefox has FireBug but all other major browsers (IE, Chrome, Safari) also have debugging tools built-in that you should check.

查看更多
栀子花@的思念
6楼-- · 2019-01-01 14:28

You could Node's util.inspect(object) to print out object's structure.

It is especially helpful when your object has circular dependencies e.g.

$ node

var obj = {
   "name" : "John",
   "surname" : "Doe"
}
obj.self_ref = obj;

util = require("util");

var obj_str = util.inspect(obj);
console.log(obj_str);
// prints { name: 'John', surname: 'Doe', self_ref: [Circular] }

It that case JSON.stringify throws exception: TypeError: Converting circular structure to JSON

查看更多
怪性笑人.
7楼-- · 2019-01-01 14:30

Use dir(object). Or you can always download Firebug for Firefox (really helpful).

查看更多
登录 后发表回答