实现函数使得将str字符串中的{}内的变量替换,如果属性不存在保持原样(比如{a.d})
1var a = { 2 b: 123, 3 c: '456', 4 e: '789', 5} 6var str=`a{a.b}aa{a.c}aa {a.d}aaaa`; 7// => 'a123aa456aa {a.d}aaaa'
参考答案:
1const fn1 = (str, obj) => { 2 let res = ''; 3 // 标志位,标志前面是否有{ 4 let flag = false; 5 let start; 6 for (let i = 0; i < str.length; i++) { 7 if (str[i] === '{') { 8 flag = true; 9 start = i + 1; 10 continue; 11 } 12 if (!flag) res += str[i]; 13 else { 14 if (str[i] === '}') { 15 flag = false; 16 res += match(str.slice(start, i), obj); 17 } 18 } 19 } 20 return res; 21} 22// 对象匹配操作 23const match = (str, obj) => { 24 const keys = str.split('.').slice(1); 25 let index = 0; 26 let o = obj; 27 while (index < keys.length) { 28 const key = keys[index]; 29 if (!o[key]) { 30 return `{${str}}`; 31 } else { 32 o = o[key]; 33 } 34 index++; 35 } 36 return o; 37} 38
最近更新时间:2021-07-07