// 方法一
let normalize = (str) => {
let arr = str.split(/[\[\]]/g).filter(Boolean)
let result = {}
let obj = result;
while(key = arr.shift()) {
obj.value = key
if(!arr.length) break;
obj.children = {} // 注意这里的obj和result是共同指向一个堆内存,obj有的result也有,并且后面改变obj的指向也不会改变result的内容,因为之前的赋值是浅拷贝
obj = obj.children // 这里的obj不仅赋值为空对象,它的指向与result的children的指向相同,后面obj有的result的children也有
}
console.log(result)
}
// 方法二
let normalize = (str) => {
let arr = str.split(/[\[\]]/g).filter(Boolean)
let result = {}
arr.reduce((pre, cur, index, self) => {
pre.value = cur
if(index !== self.length - 1) {
pre.children = {}
return pre.children
} else {
return pre
}
}, result)
console.log(result)
}
normalize('[abc[def[gh]]]')