Converting an object to a string

后端 未结 30 2355
北荒
北荒 2020-11-22 03:29

How can I convert a JavaScript object into a string?

Example:

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

Output:

30条回答
  •  庸人自扰
    2020-11-22 04:30

    Sure, to convert an object into a string, you either have to use your own method, such as:

    function objToString (obj) {
        var str = '';
        for (var p in obj) {
            if (obj.hasOwnProperty(p)) {
                str += p + '::' + obj[p] + '\n';
            }
        }
        return str;
    }
    

    Actually, the above just shows the general approach; you may wish to use something like http://phpjs.org/functions/var_export:578 or http://phpjs.org/functions/var_dump:604

    or, if you are not using methods (functions as properties of your object), you may be able to use the new standard (but not implemented in older browsers, though you can find a utility to help with it for them too), JSON.stringify(). But again, that won't work if the object uses functions or other properties which aren't serializable to JSON.

提交回复
热议问题