将对象转换为字符串

为君一笑 提交于 2020-01-07 01:02:40

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

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

例:

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

输出:

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


#1楼

看一下jQuery-JSON插件

从本质上讲,它使用JSON.stringify,但如果浏览器没有实现,则会回退到自己的解析器。


#2楼

如果你知道对象只是一个布尔,日期,字符串,数字等... javascript String()函数工作得很好。 我最近发现这对于处理来自jquery的$ .each函数的值很有用。

例如,以下内容会将“value”中的所有项目转换为字符串:

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

更多细节在这里:

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


#3楼

因为firefox没有将某些对象字符串化为屏幕对象; 如果你想得到相同的结果,例如: 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(',')+'}';
}

#4楼

这里没有一个解决方案适合我。 JSON.stringify似乎是很多人所说的,但它削减了函数,对于我在测试时尝试的一些对象和数组看起来很糟糕。

我制作了自己的解决方案,至少在Chrome中有效。 在此处发布,以便在Google上查找此内容的任何人都可以找到它。

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

编辑:我知道这个代码可以改进,但从来没有做过。 用户安德烈提出的改善这里与评论:

这是一个稍微改变的代码,它可以处理'null'和'undefined',也不会添加过多的逗号。

使用它需要您自担风险,因为我根本没有验证过。 作为评论,请随意建议任何其他改进。


#5楼

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!