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

例子:

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

输出:

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


当前回答

由于firefox没有将某些对象stringify为屏幕对象;如果你想有相同的结果,如:JSON.stringify(obj):

function objToString (obj) {
    var tabjson=[];
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            tabjson.push('"'+p +'"'+ ':' + obj[p]);
        }
    }  tabjson.push()
    return '{'+tabjson.join(',')+'}';
}

其他回答

以你为例,我想 console.log(“项目:”,o) 这是最简单的。但是, console.log("Item:" + o.toString) 也会起作用。

使用方法一可以在控制台中使用一个漂亮的下拉菜单,因此长对象可以很好地工作。

这里没有一个解决方案对我有效。JSON。stringify似乎是很多人所说的,但它削减了函数,并且在我测试时尝试的一些对象和数组似乎很坏。

我做了自己的解决方案,至少在Chrome中工作。把它贴在这里,这样任何在谷歌上看到的人都能找到它。

//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("")
}

编辑:我知道这段代码可以改进,但只是从来没有做过。用户andrey在评论中提出了一个改进:

这里有一点变化的代码,它可以处理'null'和'undefined',也没有添加过多的逗号。

使用它在你自己的风险,因为我没有验证它在所有。请随意提出任何额外的改进意见。

也许你正在寻找

JSON.stringify(JSON.stringify(obj))


"{\"id\":30}"

使用javascript String()函数

 String(yourobject); //returns [object Object]

或stringify ()

JSON.stringify(yourobject)

在你知道对象只是一个布尔值的情况下,日期,字符串,数字等…javascript的String()函数工作得很好。我最近发现这在处理来自jquery的$的值时很有用。每个函数。

例如,下面将“value”中的所有项转换为字符串:

$.each(this, function (name, value) {
  alert(String(value));
});

详情如下:

http://www.w3schools.com/jsref/jsref_string.asp