
在phonegap的开发中,有时需要知道对象的所有属性,就简单的写了个序列化的方法。
序列化方法如下:
function serialize(obj, name) {
var result = "";
function serializeInternal(o, path) {
for (p in o) {
var value = o[p];
if (typeof value != "object") {
result += "\n" + path + "." + p + " = " + value;
}
else {
if (p * 1 >= 0) {
serializeInternal(value, path + '[' + p + ']');
} else {
serializeInternal(value, path + '.' + p);
}
}
}
} serializeInternal(obj, name);
return result;
}
测试一下:
var contacts = [
{
displayName: "Mike",
phoneNumbers: [
{
type: "string",
value: "0722829323123",
pref: false
}
]
},
{
displayName: "Leo",
phoneNumbers: [
{
type: "string",
value: "03837234343",
pref: false
},
{
type: "string",
value: "005543834",
pref: true
}
]
}
]; alert(serialize(contacts, "contacts"));
运行结果: