有时需要做复杂解析的时候,用对象来操作似乎更方便些。
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.οnlοad=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>"); } }