将对象转换为字符串

如何将 JavaScript 对象转换为字符串?

例:

var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)

输出:

对象 {a = 1,b = 2} // 非常好的可读输出:)
项目:[object Object] // 不知道里面是什么:(

答案

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);
String(yourobject); //returns [object Object]
JSON.stringify(yourobject)
function objToString (obj) {
    var str = '';
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            str += p + '::' + obj[p] + '\n';
        }
    }
    return str;
}
var o = {a:1, b:2};
console.log(o);
console.log('Item: ' + o);
console.log('Item: ', o);   // :)
Object { a=1, b=2}           // useful
Item: [object Object]        // not useful
Item:  Object {a: 1, b: 2}   // Best of both worlds! :)
var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());

一种选择

console.log('Item: ' + JSON.stringify(o));

o打印为字符串

另一个选项 (如soktinpk在注释中指出的),对于控制台调试 IMO 更好:

console.log('Item: ', o);

o被打印为对象,如果您有更多字段,则可以向下钻取

//Make an object a string that evaluates to an equivalent object
//  Note that eval() seems tricky and sometimes you have to do
//  something like eval("a = " + yourString), then use the value
//  of a.
//
//  Also this leaves extra commas after everything, but JavaScript
//  ignores them.
function convertToText(obj) {
    //create an array that will later be joined into a string.
    var string = [];

    //is object
    //    Both arrays and objects seem to return "object"
    //    when typeof(obj) is applied to them. So instead
    //    I am checking to see if they have the property
    //    join, which normal objects don't have but
    //    arrays do.
    if (typeof(obj) == "object" && (obj.join == undefined)) {
        string.push("{");
        for (prop in obj) {
            string.push(prop, ": ", convertToText(obj[prop]), ",");
        };
        string.push("}");

    //is array
    } else if (typeof(obj) == "object" && !(obj.join == undefined)) {
        string.push("[")
        for(prop in obj) {
            string.push(convertToText(obj[prop]), ",");
        }
        string.push("]")

    //is function
    } else if (typeof(obj) == "function") {
        string.push(obj.toString())

    //all other values can be done with JSON.stringify
    } else {
        string.push(JSON.stringify(obj))
    }

    return string.join("")
}

如果只是输出到控制台,则可以使用console.log('string:', obj) 。注意逗号

$.each(this, function (name, value) {
  alert(String(value));
});
var obj={
name:'xyz',
Address:'123, Somestreet'
 }
var convertedString=JSON.stringify(obj) 
 console.log("literal object is",obj ,typeof obj);
 console.log("converted string :",convertedString);
 console.log(" convertedString type:",typeof convertedString);