有时需要做复杂解析的时候,用对象来操作似乎更方便些。
function object_(objectId,objectName,ObjectDesc){
var object={};
object.objectId=objectId;
object.objectName=objectName;
object.ObjectDesc=ObjectDesc;
return object;
}
上面是基本数据结构。
下面就是具体使用了。
假如有这么一串东西
var str="(productId1@productName1|productDesc1)&(productId2@productName2|productDesc2)";
需要 我们解析,我们应该如何去解析了,当然还是字符串截取,最后封闭成对象来使用最方便。
解析函数
function parseObjects(str){
var arr =[];
if(str.indexOf("&")==-1){
classInfo=parseDetail(str);
arr.push(classInfo);
}
if(str.indexOf("&")!=-1){
var temp=str.split("&");;
for(var i=0;i<temp.length;i++){
arr.push(parseDetail(temp[i]));
}
}
return arr;
}
function parseDetail(str){
var pos0=str.indexOf("@");
var pos1=str.indexOf("|");
var objectId=str.substring(1,pos0);
var objectName=str.substring(pos0+1,pos1);
var objectDesc=str.substring(pos1+1,str.length-1);
var object= object_(objectId,objectName,objectDesc);
return object;
}
使用测试:
window.onload=function(){
var str="(productId1@productName1|productDesc1)&(productId2@productName2|productDesc2)";
var arr = parseObjects(str);
for(var i=0;i<arr.length;i++){
var object_ = arr[i];
document.write("object_.objectId "+object_.objectId+",object_.objectName "+object_.objectName+" ,object_.ObjectDesc "+object_.ObjectDesc+"</br>");
}
}
本文介绍了一种将特定格式的字符串解析为JavaScript对象的方法。通过自定义函数实现字符串的拆分与重组,最终形成便于操作的对象集合。适用于需要对复合数据进行解析与处理的场景。
1617

被折叠的 条评论
为什么被折叠?



