<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
var strTest='[abc[bcd[def|xxx]]]'
function strToObj(str){
const Obj={}
const ary=str.match(/[a-z]+/g)
function getObj(index,thisObj,thisarr){
if(index<thisarr.length-1){
thisObj.value=thisarr[index];
thisObj.children={};
return getObj(++index,thisObj.children,thisarr)
}
else{
thisObj.value=thisarr[index];
return thisObj
}
}
getObj(0,Obj,ary)
return Obj
}
console.log(strToObj(strTest))
</script>
</html>
思路讲解:
1 先用正则表达式将要求的字母取出来
2.直接开始构建函数递归
递归思路如下:
递归只处理当前层次的逻辑,若发现还有字符串则生成children并开始递归。 终止条件为没有下一个字符串。