if (o == undefined) {
return ""
}
var r = []
if (typeof o == "string") return "\"" + o.replace(/([\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\""
if (typeof o == "object") {
if (!o.sort) {
for (var i in o)
r.push("\"" + i + "\":" + fn.Obj2str(o[i]))
if (!!document.all &&!/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
r.push("toString:" + o.toString.toString())
}
r = "{" + r.join() + "}"
} else {
for (var i = 0i <o.lengthi++)
r.push(fn.Obj2str(o[i]))
r = "[" + r.join() + "]"
}
return r
}
return o.toString().replace(/\"\:/g, '":""')
}
转换方式有两种:1、利用原生JSON对象,将对象转为字符串:
参考代码如下:
var jsObj = {}//定义object
jsObj.testArray = [1,2,3,4,5]//初始化
jsObj.name = 'CSS3'
jsObj.date = '8 May, 2011'
var str = JSON.stringify(jsObj)//转换成string
alert(str)//弹出提示
2、重写toString()方法:
参考代码如下:
Dog.prototype.toString = function dogToString() {
var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed
return ret
}